dplyr:计算向量中变量名称对应的变量之和

4

我需要通过编程方式添加多个变量,其名称在向量中。 例如,给定以下向量:

myvars <- c("Expectation", "Interesting", "Useful", "OralPresentation")

我该如何使用之前的向量来编写以下表达式?
df %>%
  mutate(TotalEvaluation = Expectation + Interesting + Useful + OralPresentation)
2个回答

3
我们可以在数据集的列子集之后使用rowSums
library(dplyr)
df %>% 
      mutate(TotalEvaluation = rowSums(.[myvars]))

0
你可以使用sjmisc::row_sums()函数,默认情况下将行总和附加到数据框的末尾。
library(sjmisc)
data("iris")
col <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
row_sums(iris, col, n = 1)
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species rowsums
#> 1            5.1         3.5          1.4         0.2     setosa    10.2
#> 2            4.9         3.0          1.4         0.2     setosa     9.5
#> 3            4.7         3.2          1.3         0.2     setosa     9.4
#> 4            4.6         3.1          1.5         0.2     setosa     9.4
#> 5            5.0         3.6          1.4         0.2     setosa    10.2
#> 6            5.4         3.9          1.7         0.4     setosa    11.4
#> ...

或者只是新的变量:

row_sums(iris, col, n = 1, append = FALSE)
#>     rowsums
#> 1      10.2
#> 2       9.5
#> 3       9.4
#> 4       9.4
#> 5      10.2
#> 6      11.4
#> ...

或者使用新的变量名...

row_sums(iris, col, n = 1, var = "TotalEvaluation")
#>     Sepal.Length Sepal.Width Petal.Length Petal.Width    Species TotalEvaluation
#> 1            5.1         3.5          1.4         0.2     setosa            10.2
#> 2            4.9         3.0          1.4         0.2     setosa             9.5
#> 3            4.7         3.2          1.3         0.2     setosa             9.4
#> 4            4.6         3.1          1.5         0.2     setosa             9.4
#> 5            5.0         3.6          1.4         0.2     setosa            10.2
#> 6            5.4         3.9          1.7         0.4     setosa            11.4
#> ...

row_sums() 与 dplyr 和/或管道操作符无缝配合使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接