属性表中的折叠列

古拉

我有这个prop.table(使用创建questionr::lprop):

    COMSAL
orig      1      2      3      4      5      6      7      8      9     10  Total
  10  38.31  24.11   6.85   6.45   2.58   3.98   8.72   3.98   1.69   3.32 100.00
  11  34.20  30.22   6.01   9.64   2.36   3.08   2.73   4.44   2.36   4.95 100.00
  14  37.15  30.12   4.89   8.53   3.11   3.05   2.99   3.54   3.22   3.41 100.00
  15  39.67  30.77   6.00   4.54   1.72   1.86   3.09   5.46   2.41   4.48 100.00
  21  36.52  27.27  10.12   3.71   3.65   2.10   6.92   2.96   3.21   3.54 100.00
  22  34.63  27.77   8.99   5.11   2.89   2.78   5.75   7.21   2.36   2.50 100.00

我想对第3列到第10列求和,以获得所需的输出:

    COMSAL
orig      1      2    SUM   Total
  10  38.31  24.11   37.6   100.00
  11  34.20  30.22   35.6   100.00
  14  37.15  30.12   32.7   100.00
  15  39.67  30.77   29.6   100.00
  21  36.52  27.27   36.2   100.00
  22  34.63  27.77   37.6   100.00

目前,我将某种组合与dplyr结合使用,但是它确实很长,我想知道是否有内置的软件包/函数可以做到这一点。

数据

structure(c(38.31, 34.2, 37.15, 39.67, 36.52, 34.63, 24.11, 30.22, 
30.12, 30.77, 27.27, 27.77, 6.85, 6.01, 4.89, 6, 10.12, 8.99, 
6.45, 9.64, 8.53, 4.54, 3.71, 5.11, 2.58, 2.36, 3.11, 1.72, 3.65, 
2.89, 3.98, 3.08, 3.05, 1.86, 2.1, 2.78, 8.72, 2.73, 2.99, 3.09, 
6.92, 5.75, 3.98, 4.44, 3.54, 5.46, 2.96, 7.21, 1.69, 2.36, 3.22, 
2.41, 3.21, 2.36, 3.32, 4.95, 3.41, 4.48, 3.54, 2.5, 100, 100, 
100, 100, 100, 100), .Dim = c(6L, 11L), .Dimnames = list(orig = c("10", 
"11", "14", "15", "21", "22"), COMSAL = c("1", "2", "3", "4", 
"5", "6", "7", "8", "9", "10", "Total")), class = "table")
蔡卓妍

1. baseR解决方案

cbind(x[, 1:2], rowSums(x[, 3:10]), x[, 11])

2.dplyr解决方案

library(dplyr)

as.data.frame.matrix(x) %>%
  rowwise() %>%
  mutate(SUM = sum(c_across(`3`:`10`)), .keep = "unused") %>%
  ungroup()

# # A tibble: 6 x 4
#     `1`   `2` Total   SUM
#   <dbl> <dbl> <dbl> <dbl>
# 1  38.3  24.1   100  37.6
# 2  34.2  30.2   100  35.6
# 3  37.2  30.1   100  32.7
# 4  39.7  30.8   100  29.6
# 5  36.5  27.3   100  36.2
# 6  34.6  27.8   100  37.6

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章