gpt4 book ai didi

用计数 reshape 数据

转载 作者:行者123 更新时间:2023-12-02 05:52:12 24 4
gpt4 key购买 nike

我有一个数据集,我想使用 R 中的包 reshape2 来 reshape 它,但我收到此错误:

Aggregation function missing: defaulting to length

这是我的数据的 head():

cat_one customer valor
cama A 1
cama B 1
cama C 1
mesa D 1
mesa A 1
mesa A 1

我想像这样 reshape 它,并在两个变量之间进行计数:

customer     cama    mesa
A 1 0
B 2 ...
C
D ... ...

这是我的代码:

dcast(dados_teste, cat_one ~ customer, value.var = 'valor')

我正在关注另一个 question ,但同样的解决方案对我不起作用。

最佳答案

您混淆了公式的左侧和右侧。

尝试:

library(reshape2)
dcast(dados_teste, customer ~ cat_one, value.var = "valor")
# Aggregation function missing: defaulting to length
# customer cama mesa
# 1 A 1 2
# 2 B 1 0
# 3 C 1 0
# 4 D 0 1

您提到的“错误”实际上只是一个警告,告诉您它只是计算值的数量 - 不应用任何其他函数。所以,在这种情况下,这是完全可以接受的。

如果您想删除它,请指定fun.aggregate = length

dcast(dados_teste, customer ~ cat_one, 
value.var = "valor", fun.aggregate = length)
<小时/>

如果您只计算了两列,您还可以查看table:

as.data.frame.matrix(table(dados_teste[c(2, 1)]))
# cama mesa
# A 1 2
# B 1 0
# C 1 0
# D 0 1

关于用计数 reshape 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25007317/

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