gl <- tibble::tribble(
~X4010, ~X4020, ~X4030, ~X5010, ~X5020, ~X5030, ~X5040,
1000, 100, 10, 500, 100, 50, 5,
1100, 110, 11, 550, 110, 55, 5.5,
1210, 121, 12.1, 605, 121, 60.5, 6.05,
1331, 133.1, 13.31, 665.5, 133.1, 66.55, 6.65,
1464.1, 146.41, 14.64, 732.05, 146.41, 73.2, 7.32,
1610.51, 161.05, 16.1, 805.25, 161.05, 80.52, 8.05,
1771.56, 177.15, 17.71, 885.78, 177.15, 88.57, 8.85,
1948.71, 194.87, 19.48, 974.35, 194.87, 97.43, 9.74,
2143.58, 214.35, 21.43, 1071.79, 214.35, 107.17, 10.71,
2357.94, 235.79, 23.57, 1178.97, 235.79, 117.89, 11.78
)
需要创建两个计算列,按以下方式逐行添加列:
gl %>%
mutate(C1 = X4010+X4020+X4030, C2 = X5010+X5020+X5030+X5040 )
然而,由于X变量的数量非常庞大,我不想逐个添加列,而是希望指定范围,例如X4010:X4030
或select(starts_with("X40"))
。
如何修改C1
和C2
的公式以使用范围或模式?谢谢。
期望的输出如下:
result <- tibble::tribble(
~X4010, ~X4020, ~X4030, ~X5010, ~X5020, ~X5030, ~X5040, ~C1, ~C2,
1000, 100, 10, 500, 100, 50, 5, 1110, 655,
1100, 110, 11, 550, 110, 55, 5.5, 1221, 720.5,
1210, 121, 12.1, 605, 121, 60.5, 6.05, 1343.1, 792.55,
1331, 133.1, 13.31, 665.5, 133.1, 66.55, 6.65, 1477.41, 871.8,
1464.1, 146.41, 14.64, 732.05, 146.41, 73.2, 7.32, 1625.15, 958.98,
1610.51, 161.05, 16.1, 805.25, 161.05, 80.52, 8.05, 1787.66, 1054.87,
1771.56, 177.15, 17.71, 885.78, 177.15, 88.57, 8.85, 1966.42, 1160.35,
1948.71, 194.87, 19.48, 974.35, 194.87, 97.43, 9.74, 2163.06, 1276.39,
2143.58, 214.35, 21.43, 1071.79, 214.35, 107.17, 10.71, 2379.36, 1404.02,
2357.94, 235.79, 23.57, 1178.97, 235.79, 117.89, 11.78, 2617.3, 1544.43
)