sandikou
sandikou

Reputation: 133

How to apply the eval function to a vector without looping?

I have a problem. I try to apply the eval function to a vector. But the result returned is not a vector but just one value. I explain:

Event <- c("< 0.5")
P     <- round(runif(1:10), 4)
Vec_Ev<- parse(text=paste(P, Event))

Vec_EV
expression(0.2086 < 0.5, 0.0937 < 0.5, 0.7238 < 0.5, 0.5806 < 0.5, 
0.7616 < 0.5, 0.6743 < 0.5, 0.9124 < 0.5, 0.393 < 0.5, 0.7401 < 0.5, 
0.5601 < 0.5)

And now I would like to have the result of these inequations. But the result is:

eval(Vec_Ev)
[1] FALSE

instead of a vector.

Is it possible to obtain the vector result without a loop?

Upvotes: 0

Views: 375

Answers (1)

TheComeOnMan
TheComeOnMan

Reputation: 12905

You don't need to use eval here. Simply P > 0.5 will work.

    P
    #[1] 0.3812 0.1939 0.4249 0.1729 0.4161 0.5480 0.9688 0.5409 0.7861 0.1967
    P > 0.5
    #[1] FALSE FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE

In general, it is recommended that you avoid resorting to eval. Use get, mget, assign instead if you really must.

Edit, for multiple events I'd suggest an approach as below. This is a quick fix but I think there might be a more elegant way to do it. I will update if I find something better.

library(data.table)

P  <- data.table(P1 = round(runif(1:10), 4))

# first check is for < 0.1, second is for < 0.7, third is for > 0.2
Events = c(0.1,0.7,0.2)
Compare = c('<','<','>')

for ( i in 1:length(Events))
{
P[, paste0("Event",i) := Events[i]]
if (Compare[i] == '>')
{
   P[, paste0("VecEv",i):= P1 > get( paste0('Event',i) )]
} else
{
   P[, paste0("VecEv",i):= P1 < get( paste0('Event',i) )]
}
}

 # P
        # P1 Event1 VecEv1 Event2 VecEv2 Event3 VecEv3
 # 1: 0.5328    0.1   TRUE    0.7  FALSE    0.2  FALSE
 # 2: 0.3306    0.1   TRUE    0.7  FALSE    0.2  FALSE
 # 3: 0.3132    0.1   TRUE    0.7  FALSE    0.2  FALSE
 # 4: 0.1355    0.1   TRUE    0.7  FALSE    0.2   TRUE
 # 5: 0.6571    0.1   TRUE    0.7  FALSE    0.2  FALSE
 # 6: 0.7568    0.1   TRUE    0.7   TRUE    0.2  FALSE
 # 7: 0.9472    0.1   TRUE    0.7   TRUE    0.2  FALSE
 # 8: 0.2839    0.1   TRUE    0.7  FALSE    0.2  FALSE
 # 9: 0.7823    0.1   TRUE    0.7   TRUE    0.2  FALSE
# 10: 0.1164    0.1   TRUE    0.7  FALSE    0.2   TRUE

Upvotes: 2

Related Questions