gpt4 book ai didi

r - 旋转更宽的返回 1 列?

转载 作者:行者123 更新时间:2023-12-04 09:17:47 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Collapse text by group in data frame [duplicate]

(2 个回答)


去年关闭。




我正在尝试格式化我的 base_df显示users_id由观看的节目组织。
base_df :
enter image description here

base_df <- structure(list(category = c("News", "News", "Sports", "Sports", 
"sports", "Sports", "Sports", "sports"), programs = c("News A",
"News B", "Sports A", "Sports B", "sports C", "Sports A", "Sports B",
"sports C"), users_id = c(10003831, 10003823, 10003841, 10003823,
10003851, 10003851, 10003851, 10003854)), row.names = c(NA, -8L
), class = c("tbl_df", "tbl", "data.frame"))
所需输出:
enter image description here
我想 pivot_longer可以在这里帮助我:
我试过使用它,但它返回一个只有 users_ids 的 df。我究竟做错了什么?
b <- pivot_wider(
base_df,
id_cols = users_id,
names_from = programs
)
enter image description here

最佳答案

您不需要转换为宽格式,而是聚合,即

library(dplyr)

base_df %>%
filter(category %in% c('Sports', 'sports')) %>%
group_by(users_id) %>%
summarise(how_many = n(),
which = toString(programs))


# A tibble: 4 x 3
# users_id how_many which
# <dbl> <int> <chr>
#1 10003823 1 Sports B
#2 10003841 1 Sports A
#3 10003851 3 sports C, Sports A, Sports B
#4 10003854 1 sports C


关于r - 旋转更宽的返回 1 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63154140/

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