1

I am trying to create a condition for an if-loop which is not predefined. The "length" of the condition is depending of the length of my List where prior calculated values are stored.

The proceed you can see in my code down below.

I tried to convert my character condition with some functions (expression(), eval() ...) so that the condition is readable for the if loop. But nothing works...

So I hope you can help me solving my issue.

My Code:

# the list with prior calculated values
List=list(0.96,0.89,0.78)

# rendering the condition 
condition=character()
for (m in 1:length(List)) {

    if (m==length(List)) {
        condition=paste0(condition,"List[[",m,"]]>=0.6")
    } else {
        condition=paste0(condition,"List[[",m,"]]>=0.6 && ")
    }  # end if-loop

}  # end for-loop

# to see what the condition looks like
print(condition)

# the just rendered condition in the if loop
if(condition) {
    print("do this ...")
} else {
    print("do that ...")
}  # end if-loop
kannan D.S
  • 1,107
  • 3
  • 17
  • 44
tueftla
  • 369
  • 1
  • 3
  • 16

1 Answers1

2

You need to parse the text when you use eval:

eval(parse(text=condition))

This returns TRUE in your example, so you can use it as follows:

if(eval(parse(text=condition))) {
  print("do this ...")
} else {
  print("do that ...")
}  # end if-loop

Output:

 [1] "do this ..."

You can find more information about eval here: Evaluate expression given as a string

Matt Lourens
  • 171
  • 9