简体   繁体   English

如果有 NA,如何折叠 dataframe 的列?

[英]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 + separatetidyr中:

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.

相关问题 当仅缺少两列时,如何删除 NA? - How can I remove NAs when both columns are missing only? 如何将列中的所有 NA 换成它们的中位数? - How can I exchange all the NAs in the columns for their medians? R:如何使用来自利用其他多列的条件的值替换 dataframe 列中的 NA? - R: How do I replace NAs in a dataframe column with values from conditions leveraging other multiple columns? 如何用同一数据集中其他相应多列的值替换多列中的 NA? - How can I replace NAs in multiple columns with the values from other corresponding multiple columns in the same data set? 在多个数据帧列中重新编码NA - Recode NAs in multiple dataframe columns 折叠数据框中的列(R) - Collapse columns in a dataframe (R) 如何在数据框中输入缺少的sd,然后将sd列上的NA强制作为函数自动添加到新数据框中? - How can I input missing sd in a dataframe and then enforce NAs on the column sd automatically as a function into a new data frame? 如何将冗余行折叠在一起以消除两列中的镜像 NA? - How to collapse redundant rows together to get rid of mirrored NAs in two columns? 如何将所有非数字值转换为数据帧中R中的NA? - How do I convert all nonumeric values to NAs in R in a dataframe? 如何折叠行以填充每列行数不均匀的组中的 NA? - How do I collapse rows to fill NAs in groups with uneven number of rows per column?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM