Curious
Curious

Reputation: 549

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:

enter image description here

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 :

Upvotes: 2

Views: 1118

Answers (2)

Zheyuan Li
Zheyuan Li

Reputation: 73265

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)

Upvotes: 2

Roman Luštrik
Roman Luštrik

Reputation: 70603

This works if you have a vector of values in your column of Location of different letters.

out <- sapply(c(1, 6, 7, 8), FUN = function(x) substring("FxyznADX", first = x, last = x))

do.call(paste, args = list(as.list(out), collapse = ""))
[1] "FADX"

If you have a character/factor for the values, you may need to resort to eval(parse(...)).

sapply(eval(parse(text = "c(1, 6, 7, 8)")), FUN = function(x) substring("FxyznADX", first = x, last = x))

[1] "F" "A" "D" "X"

Upvotes: 1

Related Questions