Split character string multiple times every two characters
You were actually quite close. You need to specify the separator-positions as sep = c(2,4)
instead of sep = c(2,2)
:
df <- separate(df, a, c(paste0("V",LETTERS[1:3])), sep = c(2,4))
you get:
> df VA VB VC 1 Aa Bb CC 2 AA BB CC 3 AA bb CC
In base R you could do (borrowing from @rawr's comment):
l <- ave(as.character(df$a), FUN = function(x) strsplit(x, '(?<=..)', perl = TRUE))
df <- data.frame(do.call('rbind', l))
which gives:
> df X1 X2 X3 1 Aa Bb CC 2 AA BB CC 3 AA bb CC
We could do this with base R
read.csv(text=gsub('(..)(?!$)', '\\1,', df$a,
perl=TRUE),col.names=paste0("V", LETTERS[1:3]), header=FALSE)
# VA VB VC
#1 Aa Bb CC
#2 AA BB CC
#3 AA bb CC
If we are reading directly from the file, another option is read.fwf
read.fwf(file="yourfile.txt", widths=c(2,2,2), skip=1)