Tingolfin Tingolfin - 8 days ago 6
R Question

R: Split column of data into multiple, based on nr. of characters

I have this column of data:

variable
WinterMACV
WinterMACV
WinterMACV
WinterMACV
WinterMACV
WinterMACV
...


I want to split it in 3: "Winter", "M" and "ACV". So it has to split after 6 letters, then 1, and the last 3 remain.

I've found info about splitting at a certain character like "_", "," of " ". But how about after a certain nr of characters?
I was planning to use
str_split_fixed()
from the
stringr
package. Don't know if that's possible here.

Answer

If you know for sure that the string you are splitting will always have the characters in those positions then:

df %>% mutate(v1 = substr(variable, 1, 6),
              v2 = substr(variable, 7, 7),
              v3 = substr(variable, 8, 10))