0

I have this dataframe.

dtext <- data.frame(text = c("John Marl","Anna Choi Lo","Erl Con"))

I would like to split it into more than one column using as separation the space between the words and I tried this. data.frame(do.call('rbind', strsplit(as.character(dtext$text),' ',fixed=TRUE))) However this is the output:

 X1   X2   X3
John Marl John
Anna Choi   Lo
Erl  Con  Erl

Here is the expected output

 X1   X2   X3
John Marl 
Anna Choi   Lo
Erl  Con 

How can I fix it?

Nathalie
  • 1,228
  • 7
  • 20

1 Answers1

0

You can do it with tidyr

library(tidyr)
dtext <- data.frame(text = c("John Marl","Anna Choi Lo","Erl Con"))
dtext <- dtext %>% separate(text, c('A', 'B', 'C'), fill = 'right')
dtext[is.na(dtext)] <- ''
dtext
#>      A    B  C
#> 1 John Marl   
#> 2 Anna Choi Lo
#> 3  Erl  Con

Created on 2020-02-09 by the reprex package (v0.3.0)

I have added fill = 'right' as proposed by G.Grothendiek. See also here

MarBlo
  • 4,195
  • 1
  • 13
  • 27