R:如何将字符串拆分为多个值并将生成的碎片作为列映射到数据集?

编程入门 行业动态 更新时间:2024-10-17 15:31:23
本文介绍了R:如何将字符串拆分为多个值并将生成的碎片作为列映射到数据集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 13:39:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1394425.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   并将   字符串   如何将   碎片

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!