I know I\'ve come across this problem before, but I\'m having a bit of a mental block at the moment. and as I can\'t find it on SO, I\'ll post it here so I can find it next
First of all: if you use str(df)
you'll see that df$pre
is list
. I think you want vector
(but I might be wrong).
Return to problem - in this case I will use gsub
:
df$pre <- gsub("[0-9]", "", df$lab)
df$suf <- gsub("[A-Z]", "", df$lab)
This guarantee that both columns are vectors, but it fail if your label is not from key (i.e. 'AB01B'
).
with purrr::map this would be
df$suf %>% map_chr(c(2))
for further info on purrr::map
To select the second element of each list item:
R> sapply(df$suf, "[[", 2)
[1] "00" "01" "02" "00" "01" "02" "21" "01" "03"
An alternative approach using regular expressions:
df$pre <- sub("^([A-Z]+)[0-9]+", "\\1", df$lab)
df$suf <- sub("^[A-Z]+([0-9]+)", "\\1", df$lab)