R: Split character column and create two new ones

后端 未结 4 1834
清歌不尽
清歌不尽 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 14:51

    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         
    

    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   
    

提交回复
热议问题