combine rows in data frame containing NA to make complete row

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

    We can use fill to fill all the missing values. And then filter just one row for each group.

    library(dplyr)
    library(tidyr)
    
    df2 <- df %>%
      group_by(A) %>%
      fill(everything(), .direction = "down") %>%
      fill(everything(), .direction = "up") %>%
      slice(1)
    

提交回复
热议问题