combine rows in data frame containing NA to make complete row

前端 未结 6 1940
不思量自难忘°
不思量自难忘° 2020-11-29 10:17

I know this is a duplicate Q but I can\'t seem to find the post again

Using the following data

df <- data.frame(A=c(1,1,2,2),B=c(NA,2,NA,4),C=c(3,         


        
6条回答
  •  醉梦人生
    2020-11-29 10:56

    Not tidyverse but here's one base R solution

    df <- data.frame(A=c(1,1),B=c(NA,2),C=c(3,NA),D=c(NA,2),E=c(5,NA))
    sapply(df, function(x) x[!is.na(x)][1])
    #A B C D E 
    #1 2 3 2 5 
    

    With updated data

    do.call(rbind, lapply(split(df, df$A), function(a) sapply(a, function(x) x[!is.na(x)][1])))
    #  A B C D E
    #1 1 2 3 2 5
    #2 2 4 5 3 4
    

提交回复
热议问题