【问题标题】:R: How to split a string into values and map the resultant broken pieces as columns to the dataset? [duplicate]R:如何将字符串拆分为值并将生成的碎片作为列映射到数据集? [复制]
【发布时间】:2017-07-25 18:42:55
【问题描述】:

如上图所示,我有一个列,流派,其中包含相应电影所属的流派列表。共有 19 种独特的流派。我想知道我是否可以处理这些数据,将 19 列附加到数据集,每列对应于每个流派标识符,并将相应的单元格标记为 0 或 1,表示电影从属于每个流派列。

它应该如下图所示。

【问题讨论】:

  • @akrun - 哎呀,抓错了。现在应该好多了。 SO 最近刚刚介绍了顺便编辑重复项的功能。如果您找到更好的,请随时更改它。

标签: r reshape tidyr melt


【解决方案1】:

我们可以在拆分“流派”列后这样做

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-11
    • 2019-06-11
    • 1970-01-01
    • 2023-02-06
    • 2016-10-22
    • 2021-12-28
    • 2021-10-29
    相关资源
    最近更新 更多