根据秒中的值对列进行分组 Table

Group Columns Based on Values in Second Table

我有一个包含 6 列和 >5000 行的 df。我需要在一秒钟内根据信息对列进行分组 table(样本),然后获取每组的平均值并放入新的数据框中。

列名称不会总是相同或结构如下所示:有必要根据第二个 table 中的值进行分组。

我已经搜索过论坛,但我不知道我要完成的事情的术语,结果一无所获。

感谢您的帮助!

>head(df,3)
|        | Control_Rep1 | Ethanol_Rep1 | Control_Rep2 | Ethanol_Rep2 | Control_Rep3 | Ethanol_Rep3 |
|--------|--------------|--------------|--------------|--------------|--------------|--------------|
| Q0120  | 22           | 29           | 25           | 39           | 13           | 23           |
| R0010W | 3694         | 6205         | 3322         | 7110         | 4985         | 10513        |
| R0020C | 3024         | 3564         | 2799         | 4191         | 5030         | 6214         |


>samples
| Identifier   | Treatment |
|--------------|-----------|
| Control_Rep1 | Control   |
| Ethanol_Rep1 | Ethanol   |
| Control_Rep2 | Control   |
| Ethanol_Rep2 | Ethanol   |
| Control_Rep3 | Control   |
| Ethanol_Rep3 | Ethanol   |


>Desired_Table
|        | Control    | Ethanol    |
|--------|------------|------------|
| Q0120  | 20         | 30.3333333 |
| R0010W | 4000.33333 | 7942.66667 |
| R0020C | 3617.66667 | 4656.33333 |

我们可以根据 'df' 和 'samples' 'Identifier' 的列名之间的 matching 拆分 'df',然后取 rowMeans

sapply(split.default(df,  samples$Treatment[match(names(df), 
    samples$Identifier)]), rowMeans, na.rm = TRUE)

-输出

        Control    Ethanol
Q0120    20.000   30.33333
R0010W 4000.333 7942.66667
R0020C 3617.667 4656.33333

数据

df <- structure(list(Control_Rep1 = c(22L, 3694L, 3024L), Ethanol_Rep1 = c(29L, 
6205L, 3564L), Control_Rep2 = c(25L, 3322L, 2799L), Ethanol_Rep2 = c(39L, 
7110L, 4191L), Control_Rep3 = c(13L, 4985L, 5030L), Ethanol_Rep3 = c(23L, 
10513L, 6214L)), class = "data.frame", row.names = c("Q0120", 
"R0010W", "R0020C"))

samples <- structure(list(Identifier = c("Control_Rep1", "Ethanol_Rep1", 
"Control_Rep2", "Ethanol_Rep2", "Control_Rep3", "Ethanol_Rep3"
), Treatment = c("Control", "Ethanol", "Control", "Ethanol", 
"Control", "Ethanol")), class = "data.frame", row.names = c(NA, 
-6L))