【问题标题】:How do I apply a function to one column split by each factor in another column of a data frame using ddply?如何使用 ddply 将函数应用于由数据框的另一列中的每个因子拆分的一列?
【发布时间】:2016-01-14 00:19:07
【问题描述】:

M 数据如下所示:

标签:1 1 1 2 3 2 5 5 5 2 2 3 3 5 6 7 8...
号码:132 123 838 29 1 23 0 283 238 2 123 2 ...

两列都是数字,我想为 Label 中的每个因子计算数字的分位数。

#the function I want to use to calc the quantiles
qfn <- function(x) quantile(x, probs = seq(0, 1, 0.2), na.rm = TRUE)

#Using the by function
results <- by(data$Numbers, data$Label, qfn)

我得到了正确的结果,但它是“按”类而不是数据框。

Label: 1  
0%      20%     40%     60%     80%     100%   
1.2     3.5     7.8     9.10    30.1    105.3

Label: 2  
0%      20%     40%     60%     80%     100%   
1.9     2.5     5.8     8.10    23.1    99.3

...

我如何使用 ddply 在数据框中获得这些相同的结果?

当我使用类似的东西时:

results <- ddply(data, "Label", qfn) 

我通过 Label 的因素得到了正确的分组,但在我的情况下,该函数应用于错误的列 - 当我希望将函数应用于 Numbers 时,它也应用于 Label 的值。

谢谢!

【问题讨论】:

    标签: r dataframe split plyr


    【解决方案1】:

    这让我得到了我想要的结果,但没有使用 ddply

    result <- do.call(rbind, with(data, {tapply(data$Numbers, data$Label, qfn)}))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      相关资源
      最近更新 更多