且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在没有"timevar"的情况下转置/重塑数据帧.从长格式到宽格式

更新时间:2023-12-06 16:32:40

假定您的数据位于对象dataset中:

Assuming your data is in the object dataset:

library(plyr)
## Add a 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>