Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in R Programming by (50.2k points)

I just want to split a column of strings into two sub-columns(splitting at the number of the character specified in another column)

dat <- tibble(x=c("ABCDEFG", "QRSTUVWXYZ", "FGYHGBJIOW"), y=c(4,3,8)) 

dat

 A tibble: 3 x 2

  x              y

  <chr>      <dbl>

1 ABCDEFG        4

2 QRSTUVWXYZ     3

3 FGYHGBJIOW     8

My desired outcome should look like this:

x1         x2          y

-------------------------  

ABCD       EFG         4

QRS        TUVWXYZ     3

FGYHGBJI   OW          8

I have tried using tidy::separate, but not able to get the desired output.

1 Answer

0 votes
by (108k points)

For doing that you don't need to use the tidy::separate, just use substring() inside the mutate():

dat <- dat %>% mutate(x1 = substring(x, 1, y),

                      x2 = substring(x, y + 1, nchar(x)))

If you are a beginner and want to know more about R then do check out the R programming tutorial

Browse Categories

...