r - Transpose / reshape dataframe without "timevar" from long to wide format -


i have data frame follows below long pattern:

   name          medname   name1    atenolol 25mg   name1     aspirin 81mg   name1 sildenafil 100mg   name2    atenolol 50mg   name2   enalapril 20mg 

and below (i not care if can columns named way, want data in format):

   name   medication1    medication2      medication3   name1 atenolol 25mg   aspirin 81mg sildenafil 100mg   name2 atenolol 50mg enalapril 20mg             na 

through site have become familiarish reshape/reshape2 package, , have went through several attempts try work have far failed.

when try dcast(dataframe, name ~ medname, value.var='medname') bunch of columns flags of medication names (values transposed 1 or 0) example:

 name  atenolol 25mg  aspirin 81mg name1              1             1 name2              0             0  

i tried dcast(dataset, name ~ variable) after melted dataset, spits out following (just counts how many meds each person has):

 name  medname name1        3 name2        2 

finally, tried melt data , reshape using idvar="name" timevar="variable" (of mednames), not seem built issue since if there multiple matches idvar, reshape takes first medname , ignores rest.

does know how using reshape or r function? realize there way in more messy manner loops , conditionals split , re-paste data, hoping there more simple solution. thank much!

assuming data in object dataset

library(plyr) ## add medication index data_with_index <- ddply(dataset, .(name), mutate,                           index = paste0('medication', 1:length(name)))     dcast(data_with_index, name~ index, value.var = 'medname')  ##    name   medication1    medication2      medication3 ## 1 name1 atenolol 25mg   aspirin 81mg sildenafil 100mg ## 2 name2 atenolol 50mg enalapril 20mg             <na> 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -