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

前端 未结 5 1892
不思量自难忘°
不思量自难忘° 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:17

    Here's one option. The single complication is that you need to first convert each vector to a data.frame with one row, as data.frames are what rbind.fill() expects.

    library(plyr)
    rbind.fill(lapply(sbt, function(X) data.frame(t(X))))
    #     X1       X2     X3    X4
    # 1  Sir Lancelot    the Brave
    # 2 King   Arthur     
    # 3  The    Black Knight  
    # 4  The   Rabbit     
    

    My own inclination, though, would be to just use base R, like this:

    n <- max(sapply(sbt, length))
    l <- lapply(sbt, function(X) c(X, rep(NA, n - length(X))))
    data.frame(t(do.call(cbind, l)))
    #     X1       X2     X3    X4
    # 1  Sir Lancelot    the Brave
    # 2 King   Arthur     
    # 3  The    Black Knight  
    # 4  The   Rabbit     
    

提交回复
热议问题