【问题标题】:R tapply compressing resultsR tapply 压缩结果
【发布时间】:2017-03-24 20:59:09
【问题描述】:

我正在使用 tapply 在四个独立的实验中压缩在多种条件下生长的多种植物的大型数据集。然后 tapply 吐出按物种汇总的输出。然后我试图将这些单独的物种从输出中提取出来以进行进一步分析。所以,tapply 给了我这个(来自一些虚拟数据):

> tapply(results, list(trial,condition,species),mean)
> 
, , species1

       A          B           C          D
1 -0.6357911  0.6127278 -0.23812194 -0.2769131
2 -0.3851283 -0.5955274 -0.08072294 -0.7298832
3  0.2029780 -1.0282842  0.11518872 -0.6522809
4 -0.2254586  0.4215911 -0.84305584 -0.1108188

, , species2

       A           B           C           D
1 -0.4762501  0.35766102 -0.53821633 -0.64798979
2  0.0558234  0.18602479 -0.48208241  1.09532972
3 -1.0695515  0.84401536 -0.02232301 -0.02064807
4 -0.2423312 -0.02145042 -0.18834442 -0.08221573

我得到每个物种的平均值,在每个条件下 (A-D),运行 4 个单独的实验 (1-4)。那么是否有可能,比如说,分离物种 A,然后每列平均 1-4 个?

【问题讨论】:

  • 如果您向reproducible example 提供示例输入数据和该输入所需的输出,这样我们就可以测试可能的解决方案,这样会更容易为您提供帮助。

标签: r tapply


【解决方案1】:

不完全确定您的数据的结构。但这是一个尝试。

 #Data generation function runif
 data_gen <- function() {
   x <- 
    data.frame(A=runif(4, -1.005, 1.0049),
       B=runif(4, -1.005, 1.0049),
       C=runif(4, -1.005, 1.0049),
       D=runif(4, -1.005, 1.0049))
   return(x)
  }

#Shape to similar structure
data <- list(species1=data_gen(),
         species2=data_gen(),
         species3=data_gen(),
         species4=data_gen())

#1.lapply break it up to column 1 == A 
#2.then sapply with a mean then transpose to 1 row
#3.and finally convert to data.frame
data_transf <- data.frame(t(sapply(lapply(data, '[[', 1),mean)))

#Rename columns if necessary
colnames(data_transf) <- paste0(colnames(data_transf),'_A_isolated_avg')

data_transf

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2011-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多