R: Split character column and create two new ones

后端 未结 4 1830
清歌不尽
清歌不尽 2021-01-25 14:37

R users

I have a data frame similar to this:

a <- c(\"John, 3 years\") 
b <- c(\"Mokobe, 11 years\")
c <- c(\"Ivan\")
df <- rbind(a,b,c)
df
          


        
4条回答
  •  清酒与你
    2021-01-25 15:06

    we can do a strsplit by the delimiter , and then rbind the list elements after padding with NA at the end to make length same for each list element

    lst <- strsplit(df[,1], ", ")
    do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
    #   [,1]     [,2]      
    #a "John"   "3 years" 
    #b "Mokobe" "11 years"
    #c "Ivan"   NA       
    

提交回复
热议问题