strsplit by row and distribute results by column in data.frame

前端 未结 5 1929
不思量自难忘°
不思量自难忘° 2021-02-20 15:38

So I have the data.frame

dat = data.frame(x = c(\'Sir Lancelot the Brave\', \'King Arthur\',  
                       \'The Black Knight\', \'The Rabbit\'), stri         


        
5条回答
  •  忘了有多久
    2021-02-20 16:33

    sbt = strsplit(dat$x, " ")
    sbt
    #[[1]]
    #[1] "Sir"      "Lancelot" "the"      "Brave"   
    #[[2]]
    #[1] "King"   "Arthur"
    #[[3]]
    #[1] "The"    "Black"  "Knight"
    #[[4]]
    #[1] "The"    "Rabbit"
    
    ncol = max(sapply(sbt,length))
    ncol
    # [1] 4
    
    as.data.table(lapply(1:ncol,function(i)sapply(sbt,"[",i)))
    #      V1       V2     V3    V4
    # 1:  Sir Lancelot    the Brave
    # 2: King   Arthur     NA    NA
    # 3:  The    Black Knight    NA
    # 4:  The   Rabbit     NA    NA
    

提交回复
热议问题