You can split your dataframe into pieces. Here, I am using n_start
to set the starting column and exclude those columns before that from splitting (df1[,-(1:(n_start-1))]
).
Then I loop through (map
) the sequence of the columns to slice the dataframe for every 3 columns (crating a list of dataframes).
Using map_dfc
I get the rowSums
for each of these new sliced dataframes.
I set the names to sum1, sum2, etc. and lastly bind the excluded columns before the starting point to get the final result.
library(tidyverse)
n_split <- 3
n_start <- 3
seq(n_split, ncol(df1), n_split) %>%
map(~ select(df1[,-(1:(n_start-1))],(.-(n_split-1)):.)) %>%
map_dfc(rowSums) %>%
set_names(., nm = paste0("sum", seq(ncol(.)))) %>%
bind_cols(df1[,1:(n_start-1)], .)
#> # A tibble: 5 x 4
#> ID type sum1 sum2 sum3
#> 1 ob1 1 6 15 24
#> 2 ob2 2 36 45 54
#> 3 ob3 3 66 75 84
#> 4 ob4 4 96 105 114
#> 5 ob5 5 126 135 144
Data:
df1 <- data.frame(ID = c("ob1", "ob2", "ob3", "ob4", "ob5"),
type = c(1, 2, 3, 4, 5),
a = c(1, 11, 21, 31, 41),
b = c(2, 12, 22, 32, 42),
c = c(3, 13, 23, 33, 43),
d = c(4, 14, 24, 34, 44),
e = c(5, 15, 25, 35, 45),
f = c(6, 16, 26, 36, 46),
g = c(7, 17, 27, 37, 47),
h = c(8, 18, 28, 38, 48),
i = c(9, 19, 29, 39, 49))