Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
709 views
in Technique[技术] by (71.8m points)

r - Evaluate different logical conditions from string for each row

I have a data.frame like this:

  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))

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

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.

UPDATE: I'm trying to avoid eval(parse(..)).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

One straightforward and easy solution would be using eval(parse...

library(dplyr)

df %>%
  rowwise() %>%
  mutate(goal = eval(parse(text = condition)))

# A tibble: 9 x 3
#  value condition     goal 
#  <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

However, I would recommend reading some posts before using it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...