[英]creating a dataframe from a.character column in another dataframe containing a list of elements in R
我有以下數據框(dt)
id genre score
1 "action & adventure, sci-fi, comedy" 10
2 "sci-fi" 7
3 "action & adventure" 8
4 "fantasy, comedy" 2
...
我基本上想創建一個包含每種類型的表格以及每種類型的得分總和的平均得分
在這種情況下,它將是
genre score
action & adventure 18
sci-fi 17
fantasy 2
comedy 12
我確信有一些優雅的方法可以做到這一點,但我唯一能想到的就是在 dt 中為每種類型創建一系列假人,然后將其乘以得分,然后對每列的元素求和。 預先感謝您的幫助
dplyr方式...
library(tidyverse)
d %>% separate_rows(genre,sep = ",") %>%
mutate_at(vars(genre), str_trim) %>%
group_by(genre) %>%
summarise(sum_score = sum(score, na.rm = T),
mean_score = mean(score, na.rm = T))
output 為
# A tibble: 4 x 3
genre sum_score mean_score
<chr> <dbl> <dbl>
1 action & adventure 18 9
2 comedy 12 6
3 fantasy 2 2
4 sci-fi 17 8.5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.