如何使用其他多个列中的所有非NA值创建新列? [英] How to create new column with all non-NA values from multiple other columns?
问题描述
我想创建一列d,其中包括其他列中的所有非NA值.
I would like to create a column d, which includes all the non-NA values from the other columns.
我尝试过ifelse,但无法弄清楚如何使其以正确的方式嵌套,因此也将c列中的值也包括在内.也许应该使用ifelse之外的其他东西?
I tried ifelse, but cannot figure out how to make it nested in the proper manner, so that the value in column c is included as well.. Perhaps something else than ifelse should be used?
这是一个虚拟"数据框:
Here is a "dummy" dataframe:
a <- c(NA, NA, NA, "A", "B", "A", NA, NA)
b <- c("D", "A", "C", NA, NA, NA, NA, NA)
c <- c(NA, NA, NA, NA, NA, NA, "C", NA)
data <- data.frame(a, b, c)
我希望d列看起来像这样:
I would like the d column to look like this:
data$d <- c("D", "A", "C", "A", "B", "A", "C", NA)
View(data)
推荐答案
结果表明,在NA单元格中应该只显示",而不是".
Turns out that should've just out in "" and not " " in NA cells.
如果空间不可避免,请在数据框的列上使用三边形修剪,之后再将其删除:
And if the space is not avoidable use trimws on the column of the dataframe to remove them afterwards:
data$d <- trimws(data$d)
这篇关于如何使用其他多个列中的所有非NA值创建新列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!