Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

r - How to collapse values with same ID?

I have the following dataset.

PERSONID CODE1 CODE2 CODE3 CODE4
AX1      02    NA    NA    NA
AX1      NA    03    NA    NA
AX1      NA    NA    54.3  NA
AX1      NA    NA    NA    21
AX2      NA    01    NA    NA
AX2      01    NA    NA    NA

Where for each person ID, the four possible values of CODE are spread across var CODE1-4. How can I stack it so that nevermind the position, the codes are all on the same line?

PERSONID CODE1 CODE2 CODE3 CODE4
AX1      02    03    54.3    21
AX2      01    01    NA    NA

Thank you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...