【问题标题】:Iterator ignored by ddply functionddply 函数忽略了迭代器
【发布时间】:2017-07-15 04:06:43
【问题描述】:

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

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

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

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

上面的值是正确的,但是如何转换为宽格式并不直观,也没有明确的概率是多少。

我尝试了一些 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

这个输出完全令人困惑...列名正确,但值不正确(每列重复出现)。

以上列都没有返回正确的值。

显然,我不会以正确的方式解决这个问题。但是现在我的好奇心被激起了,为什么下面的代码行返回不同的值?

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

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

谢谢。

【问题讨论】:

    标签: r scope iterator plyr


    【解决方案1】:

    这是票,来自与 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
    

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

    【讨论】:

      猜你喜欢
      • 2014-06-26
      • 2012-08-26
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2011-11-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      相关资源
      最近更新 更多