问题描述
限时送ChatGPT账号..如上图所示,我有一个流派"列,其中包含相应电影所属的流派列表.共有19种独特的流派.我想知道我是否可以处理这些数据,将 19 列附加到数据集,每列对应于每个流派标识符,并将相应的单元格标记为 0 或 1,指示电影从属到每个流派列.
As shown in the above pic, I've a column, genres, with a list of genres the corresponding movie belongs to. There are in total 19 unique genres. I'd like to know if I can manipulate this data into appending 19 columns to the data set each corresponding to each of the genres identifiers and label the corresponding cells as 0 or 1 indicating the movies affiliation to the each genre columns.
它应该类似于下图.
推荐答案
我们可以在拆分流派"列后进行此操作
We can do this after splitting the 'genres' column
library(qdapTools)
d1 <- mtabulate(strsplit(as.character(df1$genres),","))
row.names(d1) <- sub("\\s*\\(.*", "", df1$title)
<小时>
或者另一种选择是创建一个列名为流派"的矩阵,然后对拆分的字符串进行比较
Or another option is to create a matrix with column names as 'genres' and then do a comparison on the splitted string
m1 <- matrix(0, dimnames = list(sub("\\s*\\(.*", "", df1$title),
c("Adventure", "Animation", "Children",
"Comedy", "Fantasy", "Romance", "Action", "Crime", "Thriller")), ncol=9, nrow = nrow(df1))
m1 + (t(sapply(strsplit(as.character(df1$genres), ","), function(x) colnames(m1) %in% x)))
# Adventure Animation Children Comedy Fantasy Romance Action Crime Thriller
#Toy Story 1 1 1 1 1 0 0 0 0
#Jumanji 1 0 1 0 1 0 0 0 0
#Heat 0 0 0 0 0 0 1 1 1
这篇关于R:如何将字符串拆分为多个值并将生成的碎片作为列映射到数据集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论