具有共同模式的行的平均值

时间:2017-08-10 21:51:31

标签: r pattern-matching mean

我想计算列名中具有共同模式的行的平均值,对于列名称包含“_1”,“_ 2”的行的mean_A以及列名称包含“_3”和“_4”的行的mean_B。 / p>

以下是我的例子:

table1_orig

我希望以下更优雅的方式:

structure(list(sample1_type_1 = c(10.591, 41.37), sample1_type_2 = c(9.985, 
35.691), sample1_type_3 = c(9.153, 35.317), sample1_type_4 = c(7.175, 
13.781), sample2_type_1 = c(10.704, 15.821), sample2_type_2 = c(11.049, 
23.959), sample2_type_3 = c(8.261, 18.191), sample2_type_4 = c(17.316, 
21.5), sample3_type_1 = c(21.218, 22.039), sample3_type_2 = c(16.087, 
21.235), sample3_type_3 = c(12.33, 20.211), sample3_type_4 = c(11.748, 
17.264)), .Names = c("sample1_type_1", "sample1_type_2", "sample1_type_3", 
"sample1_type_4", "sample2_type_1", "sample2_type_2", "sample2_type_3", 
"sample2_type_4", "sample3_type_1", "sample3_type_2", "sample3_type_3", 
"sample3_type_4"), row.names = 1:2, class = "data.frame")

1 个答案:

答案 0 :(得分:1)

我们可以使用循环。创建vector列名称,使用Map获取相应列名称的rowMeans,并将list元素分配给新vector列名称( 'I2')

i1 <- paste0("sample", 1:3, "_type_")
i2 <- paste0(sub("type_", "", i1), rep(LETTERS[1:2], c(3, 1)))
df[i2] <- Map(function(x, y) rowMeans(df[c(x,y)]),
    paste0(i1, rep(c(1, 3), c(3, 1))), paste0(i1, rep(c(2, 4), c(3, 1))))