对列名称以特定字符串 (R) 结尾的列中的行求和

Sum rows in columns with column names ending with specific character string (R)

我正在使用以下代码计算每个子组的 z 分数。我想在末尾再添加一列,对 z 分数求和,因此以“_zscore”结尾的所有列中的所有值按行求和。我怎样才能具体 select 那些列?

(请注意,我的真实数据有更多的列,因此我希望在列名称中特别查找 select“_zscore”。)

 library(dplyr)
 set.seed(12345)
 df1 = data.frame(a=c(rep("a",8), rep("b",5), rep("c",7), rep("d",10)), 
      b=rnorm(30, 6, 2), 
      c=rnorm(30, 12, 3.5), 
      d=rnorm(30, 8, 3)
      )
 df1_z <- df1 %>%
   group_by(a) %>%
   mutate(across(b:d, list(zscore = ~as.numeric(scale(.)))))

您可以使用 select 到 select 以 "zscore" 结尾的列并使用 rowSums :

library(dplyr)
df1 %>%
  group_by(a) %>%
  mutate(across(b:d, list(zscore = ~as.numeric(scale(.))))) %>%
  ungroup %>%
  mutate(total = rowSums(select(., ends_with('zscore'))))

# A tibble: 30 x 8
#   a         b     c     d b_zscore c_zscore d_zscore  total
#   <chr> <dbl> <dbl> <dbl>    <dbl>    <dbl>    <dbl>  <dbl>
# 1 a      7.17 14.8   8.45    0.697   0.101    0.0179  0.816
# 2 a      7.42 19.7   3.97    0.841   1.17    -1.14    0.865
# 3 a      5.78 19.2   9.66   -0.108   1.05     0.332   1.28 
# 4 a      5.09 17.7  12.8    -0.508   0.732    1.14    1.36 
# 5 a      7.21 12.9   6.24    0.721  -0.329   -0.555  -0.163
# 6 a      2.36 13.7   2.50   -2.09   -0.146   -1.52   -3.76 
# 7 a      7.26 10.9  10.7     0.749  -0.774    0.593   0.567
# 8 a      5.45  6.18 12.8    -0.302  -1.80     1.14   -0.965
# 9 b      5.43 18.2   9.55   -0.445   1.12     1.34    2.02 
#10 b      4.16 12.1   4.11   -1.06    0.0776  -1.02   -2.01 
# … with 20 more rows

这里有一个data.table解决方案

它基本上与 Ronak 的答案中的代码相同,但是在 data.table 语法中。

说明
setDT(df1_z) 用于将 df1_z 设置为 data.table 格式
total := rowSums(.SD) 创建一个新列 total,其值为 .SD(一组选定列)
rowSums .SDcols = patterns("_zscore$") 定义 .SD 的选定列。在这里,名称与正则表达式模式 _zscore$ 匹配的列(这意味着:以 _zscore 结尾)

library( data.table )
setDT(df1_z)[, total := rowSums(.SD), .SDcols = patterns("_zscore$")]