在拆分之前创建一个新的因子变量:
# Make up some data
df = data.frame(Cases = sample(LETTERS[1:5], 10, replace=TRUE),
Set1 = 1:10, Set2 = 11:20)
# Duplicate your cases column
df$Cases_2 = df$Cases
# Create a new set of factor levels
levels(df$Cases_2) <- ifelse(levels(df$Cases_2) %in% c("A","B"),
"AB", levels(df$Cases_2))
temp = split(df[-c(1, 4)], df$Cases_2)
temp
# $AB
# Set1 Set2
# 3 3 13
# 5 5 15
# 6 6 16
# 8 8 18
#
# $C
# Set1 Set2
# 4 4 14
# 9 9 19
#
# $D
# Set1 Set2
# 2 2 12
# 7 7 17
# 10 10 20
#
# $E
# Set1 Set2
# 1 1 11
然后使用lapply
计算colSums
:
lapply(temp, colSums)
# $AB
# Set1 Set2
# 22 62
#
# $C
# Set1 Set2
# 13 33
#
# $D
# Set1 Set2
# 19 49
#
# $E
# Set1 Set2
# 1 11