简体   繁体   中英

How can I collapse columns of a dataframe if there are NAs?

I want to remove the NAs in the following data frame so that I'm left with 3 columns instead of 4. The names of the columns don't matter.

structure(list(Practical1 = c("65", "85", NA, "60", NA), Practical2 = c("55", 
"75", "100", NA, "35"), Practical3 = c(45.45, 50, 86.36, 40, 
72.73), Practical4 = c(NA, NA, "92", "79", "71")), class = "data.frame", row.names = c(NA, 
-5L))

I'd get something that looks like this:

pracA, pracB, pracC
65, 55, 45.45,
85, 75, 50,
100, 86.36, 92,
60, 40, 79,
35, 72.73, 71

In base R, with na.omit :

dat <- as.data.frame(t(apply(dat, 1, na.omit)))
colnames(dat) <- paste0("prac", 1:3)

output

  prac1 prac2 prac3
1    65    55 45.45
2    85    75 50.00
3   100 86.36    92
4    60 40.00    79
5    35 72.73    71

In tidyr with unite + separate :

library(tidyr)
unite(dat, "a", starts_with("Practical"), na.rm = TRUE) %>% 
  separate(a, into = str_c("prac", 1:3), sep = "_")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM