In R: get multiple rows by splitting a column using tidyr and reshape2 [duplicate]

谁都会走 提交于 2019-11-28 10:16:44

问题


This question already has an answer here:

  • Split comma-separated strings in a column into separate rows 5 answers

What is the most simpel way using tidyr or reshape2 to turn this data:

data <- data.frame(
      A=c(1,2,3),
      B=c("b,g","g","b,g,q"))

Into (e.g. make a row for each comma separated value in variable B):

  A B
1 1 b
2 1 g
3 2 g
4 3 b
5 3 g
6 3 q

回答1:


Try

library(splitstackshape)
 cSplit(data, 'B', ',', 'long')

Or using base R

lst <- setNames(strsplit(as.character(data$B), ','), data$A)
stack(lst)

Or

library(tidyr)
 unnest(lst,A)


来源:https://stackoverflow.com/questions/30818840/in-r-get-multiple-rows-by-splitting-a-column-using-tidyr-and-reshape2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!