koteletje
koteletje

Reputation: 679

Applying operators stored in a vector as text

I would like to apply operators stored in a vector operatorsUsed to series1 and series2 of the data frame df:

operatorsUsed = c('==', '>=', '<=')

series1 = 1:5
series2 = c(1, 3, 2, 4, 5)

df = data.frame(series1,
                series2,
                stringsAsFactors = FALSE)

I tried combining the parse() and eval() function:

nbrOperators  = length(operatorsUsed)

for (j in 1:nbrOperators){

  a            = df[eval(parse(text = paste0(df$series1, operatorsUsed[j], df$series2))),]
  tableCreated = paste0('b', j)
  assign(tableCreated, a)

}

But this doesn't work. With parse, I obtain for e.g. j=1

expression(1==1, 2==3, 3==2, 4==4, 5==5)

Which looks promising but then applying eval yields

[1] TRUE

Rather than the looked for

[1] TRUE FALSE FALSE TRUE TRUE

Is there away I can apply operators stored in a vector as text?

Upvotes: 1

Views: 48

Answers (1)

akrun
akrun

Reputation: 887691

We can use lapply with get

lapply(operatorsUsed, function(op) get(op)(df$series1, df$series2))
#[[1]]
#[1]  TRUE FALSE FALSE  TRUE  TRUE

#[[2]]
#[1]  TRUE FALSE  TRUE  TRUE  TRUE

#[[3]]
#[1]  TRUE  TRUE FALSE  TRUE  TRUE

as @rawr mentioned in the comments, we can also use match.fun(op) instead of get(op) in the lapply

Upvotes: 2

Related Questions