R: Split character column and create two new ones

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
  [,1]              
a "John, 3 years"   
b "Mokobe, 11 years"
c "Ivan" 

Which function should I use to split the column after comma to get:

df
[,1]    [,2]
John    3 years
Mokobe  11 years
Ivan    NA

Answer #1:

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       
Answered By: akrun

Answer #2:

with tidyr library:

library(tidyr)
df <- as.data.frame(rbind(a,b,c), stringsAsFactors=F)
separate(df, V1, c("name", "age"),sep = ",")
Answered By: Nar

Answer #3:

Just read the data directly by read.csv with fill=TRUE and header=FALSE. you can decide to change it to matrix by as.matrix()

    read.csv(text=df,fill=T,header=F,na.strings = "")
      V1        V2
1   John   3 years
2 Mokobe  11 years
3   Ivan      <NA>   

Turning to a matrix. Although not necessary

as.matrix(read.csv(text=df,fill=1,h=0,na.strings = ""))
     V1       V2         
[1,] "John"   " 3 years" 
[2,] "Mokobe" " 11 years"
[3,] "Ivan"   NA   
Answered By: Onyambu

Answer #4:

# This should work
library(stringr)

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

df<- str_split_fixed(df, ",", 2)
Answered By: Aymone Kouame
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .



# More Articles