Данные:
df <- read.table(text = 'Col_1 Col_2 Col_3 Col_4 Col_5 Col_6 Col_7 Col_8 Col_9 Col_10 Col_11 Col_12 Col_1 Col_2 Col_3 Col_4 Col_5 Col_6 Col_7 Col_8 Col_9 Col_10 Col_11 Col_12
22.43 24.53 27.61 29.31 31.35 30.27 28.40 27.67 28.22 28.10 25.52 22.97 23.55 25.43 28.60 30.26 32.93 31.27 29.35 28.81 28.89 28.93 26.63 23.60
22.89 25.00 27.32 30.12 31.82 31.71 28.92 28.00 27.98 26.83 24.02 23.54 23.75 26.12 28.19 31.31 32.99 32.44 30.05 28.82 28.63 27.58 24.57 24.30
23.11 25.23 28.47 30.24 32.52 30.65 28.53 27.26 27.65 27.02 24.40 22.35 23.83 25.98 29.27 31.19 34.15 31.88 29.57 28.23 28.03 27.38 25.03 22.80', header = TRUE, stringsAsFactors = FALSE)
Код:
library('data.table')
# split data by 12 columns
setDT(df)
split_cols <- split(seq_len(ncol(df)), ceiling(seq_along(df)/12))
df1 <- lapply(split_cols, function(x) df[, .SD, .SDcols = x ][, id := .I])
# compute row means
df2 <- lapply(df1, function(x){
x[, .(Col1_2 = rowMeans(x[, 1:2]),
Col3_5 = rowMeans(x[, 3:5]),
Col6_9 = rowMeans(x[, 6:9]),
Col10_12 = rowMeans(x[, 10:12]),
Col1_12 = rowMeans(x[, .SD, .SDcols = -'id']),
Col10_12_1_3 = rowMeans(do.call('cbind', list(x[, 10:12],
rbindlist(list(x[-1, 1:3],
data.frame(NA, NA, NA))))),
na.rm = TRUE),
id)]
})
# check for the length of df1 and df2 to be equal. If not, stop proceeding further.
stopifnot(length(df1) == length(df2))
# join df1 and df2 by id
df3 <- lapply(seq_along(df2), function(x) df1[[x]][df2[[x]], on = "id"])
# remove id column
df3 <- lapply(df3, function(x) x[, id := NULL])
# column bind all data
do.call('cbind', df3)