簡體   English   中英

如何使用ddply將函數應用於按數據幀的另一列中的每個因子划分的一列?

[英]How do I apply a function to one column split by each factor in another column of a data frame using ddply?

M數據如下所示:

標簽:1 1 1 2 3 2 5 5 5 2 2 3 3 5 6 7 8 ...
號碼:132123838 29 1 23 0283283 2123 3 ...

兩列都是數字,我想為Label中的每個因子計算Number的分位數。

#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的值。

謝謝!

這給了我想要的結果,但沒有使用ddply

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM