【发布时间】:2019-12-08 23:27:24
【问题描述】:
我有一个如下所示的数据集:
df <- tribble(
~id, ~price, ~type, ~number_of_book,
"1", 10, "X", 3,
"1", 2, "X", 1,
"1", 5, "Y", 1,
"2", 7, "X", 4,
"2", 6, "X", 1,
"2", 6, "Y", 2,
"3", 2, "X", 4,
"3", 8, "X", 2,
"3", 1, "Y", 4,
"3", 9, "Y", 5,
)
现在,我要回答这个问题:对于每个 id 和每个选定的价格组,X 占书籍的百分比,Y 占书籍的百分比?换句话说,每个id和价格组的书籍类型分布是怎样的?
要做到这一点,首先我需要在脑海中将这个数据集可视化:
agg_df <- tribble(
~type, ~id, ~less_than_two, ~two-five, ~five-six, ~more_than_six,
"X", "1", 1, 0, 0, 3,
"Y", "1", 0, 1, 0, 0,
"X", "2", 0, 0, 1, 4,
"Y", "2", 0, 0, 2, 2,
"X", "3", 4, 0, 0, 2,
"Y", "3", 4, 0, 0, 5,
)
然后,这将是我想要的数据集:
desired_df <- tribble(
~type, ~id, ~less_than_two, ~three-five, ~five-six, ~more_than_six,
"X", "1", "100%", "0%", "0%", "100%",
"Y", "1", "0%", "100%", "0%", "0%",
"X", "2", "0%", "0%", "33.3%", "66.6%",
"Y", "2", "0%", "0%", "66.6%", "33.3%",
"X", "3", "50%", "0%", "0%", "28.5%",
"Y", "3", "50%", "0%", "0%", "71.4%",
)
这个期望的数据集告诉我,当 id 为“3”并且价格箱超过 6 美元时,有两本 X 类型的书,但有五本 Y 类型的书。所以,这是分布:X(28.5%) 和 Y(71.4%)。
注意:我在这里有一个类似的问题,但现在我无法解决更复杂的操作:How to manipulate (aggregate) the data in R?
如果您能帮助我,我将不胜感激。提前致谢。
【问题讨论】:
-
对不起,我刚刚更正了数据。
-
@akrun 不幸的是,代码没有给出正确的答案。
-
@akrun 我已经在您的代码中尝试了价格和书籍数量,但仍然没有给出结果。 ://
-
你能检查一下这是否有帮助吗?
df %>% mutate(price_group = c("less_than_two", "three_five", "five_six", "more_than_six")[findInterval(price, c(2, 5, 6), left.open = TRUE) + 1]) %>% group_by(id, type, price_group) %>% summarise(number_of_book = sum(number_of_book)) %>% group_by(id, price_group) %>% mutate(n = number_of_book/sum(number_of_book) * 100) %>% select(-number_of_book) %>% pivot_wider(names_from = price_group, values_from = n) -
请注意,
findInterval已在 cmets 中提及