让我说我在R中有这个数据框
df <- read.table(text="
id a b c
1 42 3 2 NA
2 42 NA 6 NA
3 42 1 NA 7", header=TRUE)
我想将所有列计算为一,因此结果应如下所示。
id a b c d
1 42 3 2 NA 5
2 42 NA 6 NA 6
3 42 1 NA 7 8
由于存在NA值,因此我下面的代码无法正常工作。请注意,我必须选择要计数的列,因为在我的实际数据框中,我有些列不想一起计数。
df %>%
mutate(d = a + b + c)
答案 0 :(得分:2)
您可以为此使用rowSums
,它具有一个na.rm
参数来删除NA值。
df %>% mutate(d=rowSums(tibble(a,b,c), na.rm=TRUE))
或不使用仅使用基数R的dplyr
df$d <- rowSums(subset(df, select=c(a,b,c)), na.rm=TRUE)