In R, how do I translate one record with a single comma-separated field into multiple records?

前端 未结 2 1733
不思量自难忘°
不思量自难忘° 2021-01-23 15:43

I\'m working in R.

I have a dataset in which some records contain a list of cities and counties instead of just one city or county. I\'m looking for a way to transpose

相关标签:
2条回答
  • 2021-01-23 16:17
    d = as.data.frame(do.call(rbind, strsplit(dtaFrame$cityCountry, ",")))
    colnames(d) = c("city", "country")
    cbind(dtaFrame[,-which(colnames(dtaFrame)=="cityCountry",], d)
    

    should do it.

    0 讨论(0)
  • 2021-01-23 16:26

    You can use the function colsplit in package reshape2:

    x <- c("a, b", "c, d", "e")
    library(reshape2)
    colsplit(x, ",", names=c("City", "County"))
    
      City County
    1    a      b
    2    c      d
    3    e       
    
    0 讨论(0)
提交回复
热议问题