R:如何将字符串拆分为多个值并将生成的碎片作为列映射到数据集? [英] R: How to split a string into values and map the resultant broken pieces as columns to the dataset?

查看:24
本文介绍了R:如何将字符串拆分为多个值并将生成的碎片作为列映射到数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如上图所示,我有一个流派"列,其中包含相应电影所属的流派列表.共有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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆