gpt4 book ai didi

r - 计算不同的行并聚合

转载 作者:行者123 更新时间:2023-12-02 06:26:46 25 4
gpt4 key购买 nike

我有一个如下所示的数据集:

data <- tribble(
~top_1, ~top_2, ~top_3,
"A", "B", "C",
"B", "B", "B",
"C", "B", "C",
"A", "B", "B",
"A", "A", "A",
"B", "B", "A",
"C", "A", "C",
"A", "A", "A",
"A", "C", "B",
"B", "B", "C",
)

现在,我想计算每一列的不同行数,并有一个新的数据集,如下所示:

new_data <- tribble(
~product, ~top_1, ~top_2, ~top_3,
"A", .50, .30, .30,
"B", .30, .60, .30,
"C", .20, .10, .40,
)

你能帮我创建这个数据吗?

最佳答案

lvl = unique(unlist(data))
sapply(data, function(x) prop.table(table(factor(x, lvl))))
# top_1 top_2 top_3
#A 0.5 0.3 0.3
#B 0.3 0.6 0.3
#C 0.2 0.1 0.4

关于r - 计算不同的行并聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58736717/

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