Using base R:
df<- data.frame('PERSONID'=c(rep('AX1',4),rep('AX2',2)),
'CODE1'=c('02',rep(NA,4),'01'),
'CODE2'=c(NA,'03',NA,NA,'01',NA),
'CODE3'=c(NA,NA,54.3,NA,NA,NA),
'CODE4'=c(NA,NA,NA,21,NA,NA))
newDF <- Reduce(
function(x, y, ...) merge(x, y, all = TRUE, ...),
list(aggregate(CODE1~PERSONID,na.action = na.omit,df, unique),
aggregate(CODE2~PERSONID,na.action = na.omit,df, unique),
aggregate(CODE3~PERSONID,na.action = na.omit,df, unique),
aggregate(CODE4~PERSONID,na.action = na.omit,df, unique))
)
Results in:
newDF
PERSONID CODE1 CODE2 CODE3 CODE4
1 AX1 02 03 54.3 21
2 AX2 01 01 NA NA
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…