ddply函数忽略了迭代器

时间:2017-07-11 22:28:59

标签: r scope iterator plyr

在data.frame中,我试图确定另一列汇总的某些列的各种分位数。例如,假设每个iris$Petal.Length我想要iris$Species的各种分位数。

分位数的数量和值是动态的,所以最终我试图循环概率或以某种方式对其进行矢量化。这是我的矢量化尝试,但不太有用。

rm(list = ls())

require(plyr)

myDat <- iris

myProbs <- c(0, 0.15, 0.5, 1)

# This doesn't return the DF I'm looking for (where probabilities/names are identified)
petals_by_species <- ddply(myDat, "Species", summarize, Quantiles = quantile(Petal.Length, probs = myProbs))
petals_by_species

以上内容返回正确的数据,但不是优雅的格式。输出显示如下:

enter image description here

上面的值是正确的,但是如何转换为宽格式并不直观,也不清楚概率是什么。

我尝试了一些hacky解决方法,将结果合并为一些宽泛的格式,如下所示:

rm(list = ls())

require(plyr)

myDat <- iris

myProbs <- c(0, 0.15, 0.5, 1)

# So, I loop through the probabilities and combine.
for(i in 1:length(myProbs)){

  temp <- ddply(myDat, "Species", summarize, Quantiles = quantile(Petal.Length, probs = myProbs[i]))

  names(temp) <- c("Species", paste0("Prob ", myProbs[i]))

  if(i == 1){
    petals_by_species <- temp
  } else {
    petals_by_species <- merge(petals_by_species, temp)
  }
}

petals_by_species

此输出完全令人困惑......列名称正确,但值不正确(每列重复显示)。

enter image description here

以上列均未返回正确的值。

显然,我没有采用正确的方法。但是现在我的好奇心被激怒了,为什么下面的代码行会返回不同的值?

require(plyr)

myDat <- iris

myProbs <- c(0, 0.15, 0.5, 1)

intendedOutput <- ddply(myDat, "Species", summarize, Quantiles = quantile(Petal.Length, probs = myProbs[1]))
intendedOutput

i = 1
unintendedOutput <- ddply(myDat, "Species", summarize, Quantiles = quantile(Petal.Length, probs = myProbs[i]))
unintendedOutput

enter image description here

如何让ddply以我期望的方式识别我的迭代器?我应该使用不同的plyr函数吗?我试过daply没有成功。

感谢。

1 个答案:

答案 0 :(得分:0)

这是与Hadley单独通信的票:

rm(list = ls())

require(plyr)

myDat <- iris

myProbs <- c(0, 0.15, 0.5, 1)

# This doesn't return the DF I'm looking for (where probabilities/names are identified)
petals_by_species <- ddply(myDat, "Species", summarize, Quantiles = quantile(Petal.Length, probs = myProbs), probs = myProbs)
petals_by_species

然后我的输出是长格式的,报告的输入如下:

enter image description here