Build rowSums in dplyr based on columns containing pattern in their names [duplicate]

你说的曾经没有我的故事 提交于 2021-01-29 12:48:48

问题


My data frame looks something like this

USER OBSERVATION COUNT.1 COUNT.2 COUNT.3
A    1           0       1       1
A    2           1       1       2
A    3           3       0       0

With dplyr I want to build a columns that sums the values of the count-variables for each row, selecting the count-variables based on their name.

USER OBSERVATION COUNT.1 COUNT.2 COUNT.3 SUM
A    1           0       1       1       2
A    2           1       1       2       4
A    3           3       0       0       3

How do I do that?


回答1:


As you asked for a dplyr solution, you can do:

library(dplyr)

df %>% 
  mutate(SUM = rowSums(select(., starts_with("COUNT"))))

  USER OBSERVATION COUNT.1 COUNT.2 COUNT.3 SUM
1    A           1       0       1       1   2
2    A           2       1       1       2   4
3    A           3       3       0       0   3


来源:https://stackoverflow.com/questions/54286505/build-rowsums-in-dplyr-based-on-columns-containing-pattern-in-their-names

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!