combine rows in data frame containing NA to make complete row

前端 未结 6 1972
不思量自难忘°
不思量自难忘° 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:57

    A different tidyverse possibility could be:

    df %>%
     gather(var, val, -A, na.rm = TRUE) %>%
     group_by(A, var) %>%
     distinct(val) %>%
     spread(var, val)
    
          A     B     C     D     E
          
    1     1     2     3     2     5
    2     2     4     5     3     4
    

    Here it, first, performs a wide-to-long data-transformation, excluding the "A" column and removing the missing values. Second, it groups by "A" column and the variable names. Third, it removes the duplicate values. Finally, it returns the data to its original wide format.

提交回复
热议问题