如何 return 所有可能的类别由 | 分隔在一栏下

How to return all possible categories separated by | under one column

我有一个数据集 "movie",其中有一列名为 "genre",其值类似于 "Action"、"Action|Animation"、"Animation|Fantasy"。一部电影可以有多种类型。我想输出所有可能的单一类别(例如 Adventure、Fantasy)及其频率的列表。换句话说,我想知道有多少电影有类型"action",有多少电影有"fantasy"。我不关心这些组合。对此有什么建议吗?

如果没有太多流派,一个选项是使用函数 grepl(),它会告诉您特定字符串(如 'Action')是否出现在字符中(如 'Animation|Fantasy'):

library(dplyr)
library(stringr)

data.frame(
  genre = c('Action', 'Fantasy|Action', 'Animation|Fantasy')
) %>% 
  mutate(
    isAction    = grepl('Action', genre),
    isAdventure = grepl('Adventure', genre),
    isAnimation = grepl('Animation', genre),
    isComedy    = grepl('Comedy', genre),
    isFantasay  = grepl('Fantasy', genre)
  )

#               genre isAction isAdventure isAnimation isComedy isFantasay
# 1            Action     TRUE       FALSE       FALSE    FALSE      FALSE
# 2    Fantasy|Action     TRUE       FALSE       FALSE    FALSE       TRUE
# 3 Animation|Fantasy    FALSE       FALSE        TRUE    FALSE       TRUE

如果目的是找到每个流派的频率,那么我们通过分隔符 | 在 'genre' 列上做一个 split 并使用 mtabulate

library(qdapTools)
mtabulate(strsplit(as.character(df1$genre), "|", fixed = TRUE))

或使用 base R

中的 table
dat <- stack(setNames(strsplit(as.character(df1$genre), "|", 
           fixed = TRUE), seq_len(nrow(df1))))
lvls <- c("Action', 'Adventure', 'Animation', 'Comedy', 'Fantasy')
dat$values <- factor(dat$values, levels = lvls)
table(dat[2:1])

注意:假设所有类别都在数据集中找到

这是在基数 R 中使用 sapply

的一种简单方法
# sample data frame
df <- data.frame(genre=c("Action", "Action|Animation", "Animation|Fantasy"), stringsAsFactors = F)

# get uniq genre
uniq.genre <- unique(unlist(strsplit(df$genre, split = '\|')))

# get frequency
sapply(uniq.genre, function(genre) {
  sum(grepl(genre, df$genre))
})
#>    Action Animation   Fantasy 
#>         2         2         1