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

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

    Using data.table as it appears you are trying to use it.

    library(data.table)
    DT <- data.table(dat)
    DTB <- DT[, list(y = unlist(strsplit(x, ' '))), by = x]
    
    new <- rep(NA_character_,  DTB[,.N,by =x][which.max(N), N])
    names(new) <- paste0('V', seq_along(new))
    DTB[,{.new <- new 
          .new[seq_len(.N)] <- y 
           as.list(.new)} ,by= x]
    

    Or using reshape2 dcast to reshape

    library(reshape2)
    
    dcast(DTB[,list(id = seq_len(.N),y),by= x ], x ~id, value.var = 'y')
    

提交回复
热议问题