r - 如何对 `` dplyr `` or ` `tidyr`` 中的多列进行 rowSums?

标签 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

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

重要的是,该解决方案需要依赖 grep (或 dplyr:::matchesdplyr:::one_of 等)。 ) 为 rowSums 函数选择列时,并让新列的名称是动态的。

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

最佳答案

这里是一个 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

这里是基准:

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

关于r - 如何对 `` dplyr `` or ` `tidyr`` 中的多列进行 rowSums?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31843638/

相关文章:

r - 减少 R 中的内存消耗——通过引用/data.table 传递

r - 为每对二进制变量创建一个单元格计数最低的矩阵

R/dplyr : Transforming two rows into two columns

r - 如何使用 R 计算选项的响应百分比?

从宽变量组 reshape 到长变量组

r - 如何知道计算弦之间的Levenshtein距离所进行的运算?

r - knitr:使用 knit_expand 在 block 内以编程方式改变绘图高度时出现重复 block 标签错误

linux - 在 Bash 脚本中执行 R 命令?

r - 使用 dplyr 拟合多个 nls 函数

r - 使用 dplyr 汇总并统计分组 df 中唯一值的数量