1

I have data frame and I want to split column to 3 another:

df<-data.frame(x=1:5,y=paste0("num-",1:5,"-ber"))
df
  x         y
1 1 num-1-ber
2 2 num-2-ber
3 3 num-3-ber
4 4 num-4-ber
5 5 num-5-ber

Result must be something like that:

 x  y1 y2  y3
1 1 num  1 ber
2 2 num  2 ber
3 3 num  3 ber
4 4 num  4 ber
5 5 num  5 ber

I'm trying variation something like this:

df%>%
  purrr::map_chr(stringr::str_split(y,pattern="-"))

But without any positive results

Thx!

jyjek
  • 2,627
  • 11
  • 23

1 Answers1

4

We can use separate from tidyr which automatically picks up the delimiter if the sep is not specified. In this case, it is -

library(dplyr)
library(tidyr)
df %>% 
    separate(y, into= paste0('y', 1:3))
#  x  y1 y2  y3
#1 1 num  1 ber
#2 2 num  2 ber
#3 3 num  3 ber
#4 4 num  4 ber
#5 5 num  5 ber

Or a base R option would be to read with read.table specifying the sep as - and cbind with the 'x' column

cbind(df['x'], read.table(text=as.character(df$y), sep="-", col.names = paste0("y", 1:3)))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • this is very good decision, but I hope to see answer using `purrr` – jyjek Feb 14 '18 at 18:22
  • @jyjek It will be inefficient to loop through each element in `map` and then do the split. But, if you insist `df %>% pull(y) %>% map_df(~ str_split(.x, '-')[[1]] %>% t %>% as_tibble ) %>% rename_all(funs(paste0("y", 1:3))) %>% bind_cols(df['x'], .)` – akrun Feb 15 '18 at 06:40
  • 1
    Thx a lot for this – jyjek Feb 15 '18 at 07:37