gpt4 book ai didi

r - 不使用ddply和merge计算 "group characteristics"

转载 作者:行者123 更新时间:2023-12-04 09:04:10 25 4
gpt4 key购买 nike

我想知道是否有比我通常采用的方法更直接的方法来计算某种类型的变量......

下面的例子可能最好地解释了它。我有一个包含 2 列的数据框(水果以及水果是否腐烂)。我想为每一行添加例如同类别水果腐烂的百分比。例如,苹果有 4 个条目,其中 2 个是腐烂的,因此苹果的每一行应为 0.5。目标值(仅作为说明)包含在“预期结果”列中。

我之前已经通过以下方式解决了这个问题
* 在水果变量上使用“ddply”命令(以 sum/lenght 作为函数),创建一个新的 3*2 数据框
* 使用“合并”命令将这些值链接回旧数据帧。

这感觉像是一种迂回的方式,我想知道是否有更好/更快的方法来做到这一点!理想情况下是一种通用方法,如果需要确定是否使用百分比而不是百分比,则可以轻松调整。所有的水果都烂了,任何水果都烂了,等等等等......

提前谢谢了,


    Fruit Rotten Desired_Outcome_PercRotten
1 Apple 1 0.5
2 Apple 1 0.5
3 Apple 0 0.5
4 Apple 0 0.5
5 Pear 1 0.75
6 Pear 1 0.75
7 Pear 1 0.75
8 Pear 0 0.75
9 Cherry 0 0
10 Cherry 0 0
11 Cherry 0 0

#create example datagram; desired outcome columns are purely inserted as illustrative of target outcomes
Fruit=c(rep("Apple",4),rep("Pear",4),rep("Cherry",3))
Rotten=c(1,1,0,0,1,1,1,0,0,0,0)
Desired_Outcome_PercRotten=c(0.5,0.5,0.5,0.5,0.75,0.75,0.75,0.75,0,0,0)
df=as.data.frame(cbind(Fruit,Rotten,Desired_Outcome_PercRotten))
df

最佳答案

您只需使用 ddply 即可完成此操作和 mutate :

# changed summarise to transform on joran's suggestion
# changed transform to mutate on mnel's suggestion :)
ddply(df, .(Fruit), mutate, Perc = sum(Rotten)/length(Rotten))

# Fruit Rotten Perc
# 1 Apple 1 0.50
# 2 Apple 1 0.50
# 3 Apple 0 0.50
# 4 Apple 0 0.50
# 5 Cherry 0 0.00
# 6 Cherry 0 0.00
# 7 Cherry 0 0.00
# 8 Pear 1 0.75
# 9 Pear 1 0.75
# 10 Pear 1 0.75
# 11 Pear 0 0.75

关于r - 不使用ddply和merge计算 "group characteristics",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15467219/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com