我们可以在拆分“流派”列后这样做
library(qdapTools)
d1 <- mtabulate(strsplit(as.character(df1$genres),","))
row.names(d1) <- sub("\\s*\\(.*", "", df1$title)
或者另一种选择是创建一个列名为“流派”的矩阵,然后对拆分后的字符串进行比较
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