gpt4 book ai didi

R:通过选择某些行来生成频率表

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

我有一个数据集 D 的最小示例,它看起来像:

 score person freq
10 1 3
10 2 5
10 3 4
8 1 3
7 2 2
6 4 1

现在,我希望能够针对人绘制分数 = 10 的频率。

但是,如果我这样做:
#My bad, turns out the next line only works for matrices anyway:
#D = D[which(D[,1] == 10)]

D = subset(D, score == 10)

然后我得到:
score person freq
10 1 3
10 2 5
10 3 4

但是,这就是我想得到的:
score person freq
10 1 3
10 2 5
10 3 4
10 4 0

在 R 中,我有什么快速而轻松的方法可以做到这一点吗?

最佳答案

这是一个基本的R方法:

subset(as.data.frame(xtabs(freq ~ score + person, df)), score == 10)
# score person Freq
#4 10 1 3
#8 10 2 5
#12 10 3 4
#16 10 4 0

关于R:通过选择某些行来生成频率表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37464674/

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