我正在尝试为一个没有预定义的if循环创建一个条件。条件的“长度”取决于存储先前计算值的列表的长度。
你可以在下面的代码中看到这一过程。
我尝试用一些函数(expression(),eval() ...)来转换我的字符条件。以便该条件对于if循环是可读的。但都不管用..。
所以我希望你能帮我解决我的问题。
我的代码:
# 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发布于 2018-09-07 17:36:32
使用eval时,需要对文本进行解析:
eval(parse(text=condition))这在您的示例中返回TRUE,因此您可以按如下方式使用它:
if(eval(parse(text=condition))) {
print("do this ...")
} else {
print("do that ...")
} # end if-loop输出:
[1] "do this ..."你可以在这里找到更多关于eval的信息:Evaluate expression given as a string
https://stackoverflow.com/questions/52219541
复制相似问题