从每一行的字符串中评估不同的逻辑条件 [英] Evaluate different logical conditions from string for each row
问题描述
我有这样的data.frame
:
value condition
1 0.46 value > 0.5
2 0.96 value == 0.79
3 0.45 value <= 0.65
4 0.68 value == 0.88
5 0.57 value < 0.9
6 0.10 value > 0.01
7 0.90 value >= 0.6
8 0.25 value < 0.91
9 0.04 value > 0.2
structure(list(value = c(0.46, 0.96, 0.45, 0.68, 0.57, 0.1, 0.9,
0.25, 0.04), condition = c("value > 0.5", "value == 0.79", "value <= 0.65",
"value == 0.88", "value < 0.9", "value > 0.01", "value >= 0.6",
"value < 0.91", "value > 0.2")), class = "data.frame", row.names = c(NA,
-9L))
我想评估condition
列中每一行的字符串.
I would like to evaluate the strings in the condition
column for every row.
所以结果看起来像这样.
So the result would look like this.
value condition goal
1 0.46 value > 0.5 FALSE
2 0.96 value == 0.79 FALSE
3 0.45 value <= 0.65 TRUE
4 0.68 value == 0.88 FALSE
5 0.57 value < 0.9 TRUE
6 0.10 value > 0.01 TRUE
7 0.90 value >= 0.6 TRUE
8 0.25 value < 0.91 TRUE
9 0.04 value > 0.2 FALSE
我想在dplyr
框架中有一个方便的NSE解决方案.我已经尝试过!!
和expr()
等.尝试使用
I suppose there is a handy NSE solution within the dplyr
framework. I have experimented with !!
and expr()
and others. I got some promising results when trying to subset by condition
using
result <- df[0,]
for(i in 1:nrow(df)) {
result <- rbind(result, filter_(df[i,], bquote(.(df$condition[i]))))
}
但是我不喜欢这种解决方案,也不完全是我想要的解决方案.
But I don't like the solution and it's not exactly what I'm after.
我希望有人能提供帮助.
I hope someone can help.
更新:我正试图避免使用eval(parse(..))
.
UPDATE: I'm trying to avoid eval(parse(..))
.
推荐答案
不确定是否要查找类似的内容,但是,您也可以使用lazyeval
中的lazy_eval()
:
Not entirely sure whether you are looking for something like this, however, you can also use lazy_eval()
from lazyeval
:
df %>%
rowwise() %>%
mutate(res = lazy_eval(sub("value", value, condition)))
value condition res
<dbl> <chr> <lgl>
1 0.46 value > 0.5 FALSE
2 0.96 value == 0.79 FALSE
3 0.45 value <= 0.65 TRUE
4 0.68 value == 0.88 FALSE
5 0.570 value < 0.9 TRUE
6 0.1 value > 0.01 TRUE
7 0.9 value >= 0.6 TRUE
8 0.25 value < 0.91 TRUE
9 0.04 value > 0.2 FALSE
即使它非常接近eval(parse(...))
,也有可能使用rlang
中的parse_expr()
:
And even though it is very close to eval(parse(...))
, a possibility is also using parse_expr()
from rlang
:
df %>%
rowwise() %>%
mutate(res = eval(rlang::parse_expr(condition)))
这篇关于从每一行的字符串中评估不同的逻辑条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!