对 R 中的列组合执行多个操作



使用以下命令,我构建了一个具有命名系列的示例数据框,然后我使用所有可能的列名对制作了另一个帧。

dataset <- data.frame(randwalk(10), randwalk(10), randwalk(10), randwalk(10), randwalk(10))
colnames(dataset) <- c( "one", "two", "three", "four", "five")
datasetpairs = data.frame(t(combn(colnames(dataset), 2)))
colnames(datasetpairs) <- c("numerator", "denominator")

它们看起来像这样:

head(dataset)
        one       two    three     four     five
1 1.0000000 1.0000000 1.000000 1.000000 1.000000
2 1.0055678 0.9866026 1.004089 1.007859 1.004886
3 1.0137884 0.9794308 1.013057 1.011453 1.003129
4 1.0043928 0.9838919 1.026479 1.025951 1.005845
5 0.9942291 0.9839125 1.026769 1.030824 1.007177
6 0.9993814 0.9618307 1.035784 1.037156 1.026317
head(datasetpairs)
  numerator denominator
1       one         two
2       one       three
3       one        four
4       one        five
5       two       three
6       two        four

我想做的是向"数据集对"添加几列,以存储每个列对比率的平均值、最大值和最小值。我可以通过从每行中管道输入值来获取单个图形,因此我可以执行 FOR 循环,但我尝试这样做矢量样式,例如:

datasetpairs$mean <- mean( dataset[[datasetpairs$numerator]] / 
dataset[[datasetpairs$demonimator]]

但这给了我一个错误。此外,我真正想做的是只计算两列的比率一次,并在继续下一个之前存储来自分析的几个值而不存储它,因为实际上我的数据集太大,无法事先计算所有可能的比率组合。 在不诉诸循环的情况下做到这一点的优雅方法是什么?感谢任何可以提供帮助的人!

下面是一个使用 data.table 的解决方案(因为它有很多分组操作的速度很快)和一个自定义函数来进行分析。这样,您的代码是可读的,并且在继续之前只需计算一次每个比率。

library(data.table)
#create data
set.seed(123)
dataset <- data.frame(matrix(runif(50),ncol=5))
colnames(dataset) <- c( "one", "two", "three", "four", "five")
#custom function to process two vectors:
process_data <- function(v1,v2){
  ratio <- v1/v2
  res <- list(mean=mean(ratio),min=min(ratio),max=max(ratio))
  return(res)
}
datasetpairs = data.table(t(combn(colnames(dataset), 2)))
colnames(datasetpairs) <- c("numerator", "denominator")
#run the analysis
datasetpairs[,process_data(dataset[[numerator]],dataset[[denominator]]),by=.(numerator,denominator)]

最新更新