In the spirit of similar questions along these lines here and here , I would like to be able to sum across a sequence of columns in my data_frame
& create a new column:
df_abc = data_frame(
FJDFjdfF = seq(1:100),
FfdfFxfj = seq(1:100),
orfOiRFj = seq(1:100),
xDGHdj = seq(1:100),
jfdIDFF = seq(1:100),
DJHhhjhF = seq(1:100),
KhjhjFlFLF = seq(1:100),
IgiGJIJFG= seq(1:100),
)
# this does what I want
df_abc %>%
mutate(
sum_1 = orfOiRFj + xDGHdj + jfdIDFF + DJHhhjhF
)
Clearly, if there are a lot of variables in this sequence, typing them out is not feasible. Also, the names of the variables are not regex-friendly, so cannot be selected by a rule, other than the fact that they occur in a sequence.
I am hoping that there exists an abstraction in the tidyverse, that allows something like:
df_abc %>%
mutate(
sum_1 = sum(orfOiRFj:DJHhhjhF)
)
Thanks.
You can use rowSums
to do that:
# option 1
df_abc %>% mutate(sum_1 = rowSums(.[3:6]))
# option 2
df_abc %>% mutate(sum_1 = rowSums(select(.,orfOiRFj:DJHhhjhF)))
The result:
# A tibble: 100 x 9
FJDFjdfF FfdfFxfj orfOiRFj xDGHdj jfdIDFF DJHhhjhF KhjhjFlFLF IgiGJIJFG sum_1
<int> <int> <int> <int> <int> <int> <int> <int> <dbl>
1 1 1 1 1 1 1 1 1 4
2 2 2 2 2 2 2 2 2 8
3 3 3 3 3 3 3 3 3 12
4 4 4 4 4 4 4 4 4 16
5 5 5 5 5 5 5 5 5 20
6 6 6 6 6 6 6 6 6 24
7 7 7 7 7 7 7 7 7 28
8 8 8 8 8 8 8 8 8 32
9 9 9 9 9 9 9 9 9 36
10 10 10 10 10 10 10 10 10 40
# ... with 90 more rows
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.