Split strings into columns in R where each string has a potentially different number of column entries

前端 未结 3 711
情歌与酒
情歌与酒 2021-01-12 17:43

I\'ve got a data frame that\'s got the following form

pages                         count
[page 1, page 2, page 3]      23
[page 2, page 4]              4
[p         


        
3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-12 18:05

    My "splitstackshape" package has a function that addresses this kind of problem. The relevant function in this case is concat.split and works as follows (using "myDat" from Ricardo's answer):

    # Get rid of "[" and "]" from your "pages" variable
    myDat$pages <- gsub("\\[|\\]", "", myDat$pages)
    # Specify the source data.frame, the variable that needs to be split up
    #   and whether to drop the original variable or not
    library(splitstackshape)
    concat.split(myDat, "pages", ",", drop = TRUE)
    #   count pages_1 pages_2 pages_3
    # 1    23  page 1  page 2  page 3
    # 2     4  page 2  page 4        
    # 3    12  page 1  page 3  page 4
    

提交回复
热议问题