gpt4 book ai didi

r - 基于第三个变量(数字)的列联表

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

不久前,我问了一个有关创建购物篮数据的问题。现在我想创建一个类似的 data.frame,但基于第三个变量。不幸的是我在尝试时遇到了问题。上一个问题:Effecient way to create market basket matrix in R
@shadow 和 @SimonO101 给了我很好的答案,但我无法正确更改他们的 anwser。我有以下数据:

Customer <- as.factor(c(1000001,1000001,1000001,1000001,1000001,1000001,1000002,1000002,1000002,1000003,1000003,1000003))
Product <- as.factor(c(100001,100001,100001,100004,100004,100002,100003,100003,100003,100002,100003,100008))
input <- data.frame(Customer,Product)

我现在可以通过以下方式创建列联表:

input_df <- as.data.frame.matrix(table(input))

但是我有第三个(数字)变量,我想将其作为表中的输出。

Number <- c(3,1,-4,1,1,1,1,1,1,1,1,1) 
input <- data.frame(Customer,Product,Number)

现在代码(当然,现在有3个变量)不再起作用了。我正在寻找的结果具有唯一的客户作为行名称和唯一的产品作为列名称。并以 Number 作为值(如果不存在则为 0),该数字可以通过以下方式计算:

input_agg <- aggregate( Number ~ Customer + Product, data = input, sum)

希望我的问题很清楚,如果有不清楚的地方请评论。

最佳答案

您可以使用 xtabs 来实现:

R> xtabs(Number~Customer+Product, data=input)

Product
Customer 100001 100002 100003 100004 100008
1000001 0 1 0 2 0
1000002 0 0 3 0 0
1000003 0 1 1 0 1

关于r - 基于第三个变量(数字)的列联表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19520525/

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