[英]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.我想删除以下数据框中的 NA,以便留下 3 列而不是 4 列。列的名称无关紧要。
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
:在基数 R 中,使用na.omit
:
dat <- as.data.frame(t(apply(dat, 1, na.omit)))
colnames(dat) <- paste0("prac", 1:3)
output 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
:在带有unite
+ separate
的tidyr
中:
library(tidyr)
unite(dat, "a", starts_with("Practical"), na.rm = TRUE) %>%
separate(a, into = str_c("prac", 1:3), sep = "_")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.