我有一个包含 21 列的 data.frame,每三列代表一个特定的时间点。我想计算这些一式三份中每一个的平均值。
geneName t11 t12 t13 t21 t22 t23 t31 t32 t33 t41 t42 t43 t51 t52 t53 t61 t62 t63
gene1 gene1 3296 5133 3466 2166 1759 2099 1916 1379 1570 2533 1794 1016 800 79 648 99 60 152
gene2 gene2 4210 5505 4173 2736 2748 3052 2409 1944 2237 1158 3475 1488 4023 102 940 265 365 124
...
Run Code Online (Sandbox Code Playgroud)
t1在上面的例子中,我想计算三个、t2、t3等的平均值。
这是一个基本的 R 方法 -
# Column numbers to be ignored from the calculation
columns_not_included <- 1
# Keep only subset of dataset that we need
tmp <- df[-columns_not_included]
cbind.data.frame(df[columns_not_included],
sapply(split.default(tmp,
sub('\\d$', '', names(tmp))), rowMeans, na.rm =TRUE))
# geneName t1 t2 t3 t4 t5 t6
#1 gene1 3965.000 2008.000 1621.667 1781.000 509.000 103.6667
#2 gene2 4629.333 2845.333 2196.667 2040.333 1688.333 251.3333
Run Code Online (Sandbox Code Playgroud)
sub('\\d$', '', names(tmp))将删除列名称的最后一个数字,以便t11,t12和t13都将仅返回t1并且对于传递给split.default基于这些组拆分数据帧列表中的数据的其他组相同。对于每个组,我们使用 计算行均值rowMeans。