我试图学习如何在R中使用across()函数,我想用它做一个简单的rowsum()。然而,我一直得到这个错误:
错误:mutate()输入的问题。X ' X '必须是数字?
输入..2
is
然而,我所有的相关列都是数字。任何帮助,任何解释,我为什么会得到这个错误将非常感谢!
下面是一个可复制的例子:
library(dplyr)
test <- tibble(resource_name = c("Justin", "Corey", "Justin"),
project = c("P1", "P2", "P3"),
sep_2021 = c(1, 2, NA),
oct_2021 = c(5, 2, 1))
test %>%
select(resource_name, project, sep_2021, oct_2021) %>%
mutate(total = across(contains("_20")), rowSums(., na.rm = TRUE))
这就是为什么我要这么做
answer <- tibble(resource_name = c("Justin", "Corey", "Justin"),
project = c("P1", "P2", "P3"),
sep_2021 = c(1, 2, NA),
oct_2021 = c(5, 2, 1),
total = c(6, 4, 1))
注意:我的真实数据集有很多列,顺序是可变的。因为我真的想使用包含(“_20”)部分的代码,而不是索引。
# # #我们可能使用adorn_totals
library(dplyr)
library(janitor)
test %>%
adorn_totals("col", name = "total")
对于rowsum和跨语法将是
resource_name project sep_2021 oct_2021 total
Justin P1 1 5 6
Corey P2 2 2 4
Justin P3 NA 1 1
与产出
test %>%
mutate(total = rowSums(across(contains("_20")), na.rm = TRUE))
在OP的代码中,across选择了列,但是rowsum是对整个数据(。)而不是所选择的数据进行的
# A tibble: 3 x 5
resource_name project sep_2021 oct_2021 total
<chr> <chr> <dbl> <dbl> <dbl>
1 Justin P1 1 5 6
2 Corey P2 2 2 4
3 Justin P3 NA 1 1
# # #更新:
正如akrun所评论的(见评论)我们使用
这里是另一个dplyr选项来计算行和(用rowwise和sum:c_across
test %>%
rowwise() %>%
mutate(total = sum(c_across(contains("_20")), na.rm = TRUE))
test %>%
rowwise() %>%
mutate(total = sum(across(contains("_20")), na.rm = TRUE))
resource_name project sep_2021 oct_2021 total
<chr> <chr> <dbl> <dbl> <dbl>
1 Justin P1 1 5 6
2 Corey P2 2 2 4
3 Justin P3 NA 1 1