【问题标题】:Mean for rows with common pattern具有共同模式的行的平均值
【发布时间】:2017-08-11 11:46:13
【问题描述】:

我想计算列名中具有共同模式的行的平均值,mean_A 用于列名包含“_1”、“_2”的行,而 mean_B 用于列名包含“_3”和“_4”的行。

这是我的例子:

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")

我会欣赏比以下更优雅的方式:

df$sample1_A <- rowMeans(subset(df, select = c(sample1_type_1, sample1_type_2)), na.rm = TRUE)
df$sample2_A <- rowMeans(subset(df, select = c(sample2_type_1, sample2_type_2)), na.rm = TRUE)
df$sample3_A <- rowMeans(subset(df, select = c(sample3_type_1, sample3_type_2)), na.rm = TRUE)
df$sample1_B <- rowMeans(subset(df, select = c(sample1_type_3, sample1_type_4)), na.rm = TRUE)
...

【问题讨论】:

    标签: r pattern-matching mean


    【解决方案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))))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多