如何将R变量作为代码行?

时间:2014-05-26 07:39:07

标签: r subset

我试图在子集函数上创建循环,为此我将子集规则存储在变量中(从具有所有条件的Mat列表中获取数据):

all <- paste("newdat, ", Mat[,2][j],  sep="")
all 

[1] "newdat, newdat$num_recent_claims>=2.5 & newdat$tpv_max_ratio<0.0141 & newdat$num_recent_claims>=5.5 "

如何在子集函数中使用该变量,以便将字符串用作子集条件? 目前无效:

badpop <- subset(all)

任何想法?

2 个答案:

答案 0 :(得分:1)

all <- "newdat, newdat$num_recent_claims>=2.5 & newdat$tpv_max_ratio<0.0141 & newdat$num_recent_claims>=5.5 "

需要生成带有代码的文本来执行它:

all2 <- unlist(strsplit(all, ","))
txt <- paste0 (all2[1], "[", all2[2], ", ]")

> txt
[1] "newdat[ newdat$num_recent_claims>=2.5 & newdat$tpv_max_ratio<0.0141 & newdat$num_recent_claims>=5.5 , ]"

并运行书面代码:

badpop <- eval(parse(text=txt))

答案 1 :(得分:-1)

您可以尝试eval(parse())但请记住

fortunes::fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

fortunes::fortune(181)

Personally I have never regretted trying not to underestimate my own future stupidity.
   -- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering a
      question triggered by the infamous fortune(106))
      R-help (January 2007)