Q:

How to use substring function in R when you have a vector?

I need to use substring function to extract characters by location from a data frame as shown in the picture:

Here is the code that I used:
substring(df$Text1,
          df$'Location of Different Letters',
          df$'Location of Different Letters')

substring function introduced NAs in every row where the numbers are in character string format. Any suggestion how to make it work? Using as.integer on column "Location of Different Letters" doesn't work because of the c() and :

A:

You have Location of different letters as a character column, which will make things a bit of ugly as we have to use eval(parse(..)).
## create a index list
cmd <- paste0("list(", toString(df$"Location of different letters"), ")")
# [1] "list(4, c(1,6,7,8), 3:6)"
ind <- eval(parse(text = cmd))
## split your strings
s <- strsplit(df$Text1, "")
## use `mapply`
set1 <- mapply("[", s, ind)

## now compare with `Text2` to get different letters
set2 <- strsplit(df$Text2, "")
mapply(function (a, b) paste0(setdiff(a, b), collapse = ""), set1, set2)
# [1] "d"    "FADX" "123" 

Data:
df <- data.frame(Text1 = c("abcd", "FxyznADX", "Don123"),
                 Text2 = c("abc", "xyzn", "Don"),
                 "Location of different letters" = c("4", "c(1,6,7,8)", "3:6"),
                 check.names = FALSE)

