如何在``dplyr``或``tidyr``中的多列上进行rowSums?

ken*_*nyB 4 r dplyr tidyr

例如,是否可以在dplyr中执行此操作:

new_name <- "Sepal.Sum"
col_grep <- "Sepal"

iris <- cbind(iris, tmp_name = rowSums(iris[,grep(col_grep, names(iris))]))
names(iris)[names(iris) == "tmp_name"] <- new_name
Run Code Online (Sandbox Code Playgroud)

这会将名称中包含"Sepal"的所有列相加,并创建一个名为"Sepal.Sum"的新变量.

重要的是,该解决方案需要依靠一个grep(或dplyr:::matches,dplyr:::one_of等)选择用于该列时rowSums的功能,并有新的列的名称是动态的.

我的应用程序在循环中创建了许多新列,因此可以使用更好的解决方案mutate_each_来生成许多新列.

Sab*_*DeM 9

这里是一个使用内部dplyr使用的contains特殊功能的解决方案select.

 iris %>% mutate(Sepal.Sum = iris %>% rowwise() %>% select(contains("Sepal")) %>% rowSums()) -> iris2
 head(iris2)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species Sepal.Sum
1          5.1         3.5          1.4         0.2  setosa       8.6
2          4.9         3.0          1.4         0.2  setosa       7.9
3          4.7         3.2          1.3         0.2  setosa       7.9
4          4.6         3.1          1.5         0.2  setosa       7.7
5          5.0         3.6          1.4         0.2  setosa       8.6
6          5.4         3.9          1.7         0.4  setosa       9.3
Run Code Online (Sandbox Code Playgroud)

这里的基准:

Unit: milliseconds
                                                                                                      expr
 iris2 <- iris %>% mutate(Sepal.Sum = iris %>% rowwise() %>% select(contains("Sepal")) %>%      rowSums())
      min      lq     mean   median       uq      max neval
 1.816496 1.86304 2.132217 1.928748 2.509996 5.252626   100
Run Code Online (Sandbox Code Playgroud)