Search code examples
rstringparsingexpressioneval

Error in parse(text = expression) : <text>:2:1: unexpected ','


Solutions to prior similar questions 1 and 2 do not work.

f_letter <- 'a'
l_letter <- 'c'
sep <- c(':', ',')
to <- 1
and <- 2

expression <- noquote(c(which(letters == f_letter), 
   sep[and], which(letters == l_letter)))
expression

eval(parse(text=expression))

Error in parse(text = expression) : :2:1: unexpected ',' 1: 1 2: , ^

Expected output:

#for sep[and]
1 3

#for sep[to]
1 2 3

Solution

  • Based on question 1, you could try a similar approach.

    First you should use c instead of , since the first is a function, the latter is not. So you could do something like this:

    f_letter <- 'a'
    l_letter <- 'c'
    sep <- c(":", "c")
    to <- 1
    and <- 2
    
    do.call(sep[to], list( which(letters == f_letter), which(letters == l_letter) ))
    [1] 1 2 3
    
    
    do.call(sep[and], list( which(letters == f_letter), which(letters == l_letter) ))
    [1] 1 3