2015-07-19 30 views
0

我想从参数化的数据帧中提取信息。 那就是:以参数方式从数据帧中提取信息(通过菜单选择)

A <- c(3, 10, 20, 30, 40) 
B <- c(30, 100, 200, 300, 400) 
DF <- data.frame(A, B) 

DF[A%in%c(1, 2, 3, 4, 5), ] # it works 

# But what if this is the case, 
# which comes for example out of a user-menu selection: 
m <- "A%in%" 
k <- c(1, 2, 3, 4, 5) 

# How can we make something like that work: 
DF[eval(parse(text=c(m, k))), ] 

回答

2

这工作:

DF[eval(parse(text = paste0(m, deparse(k)))), ] 
# A B 
#1 3 30 

然而,eval(parse())应尽量避免。也许这将是你的替代方案?

x <- "A" 
fun <- "%in%" 
k <- c(1, 2, 3, 4, 5) 
DF[getFunction(fun)(get(x), k), ] 
# A B 
#1 3 30 
2

此外,

DF[eval(parse(text=paste(m, substitute(k)))),] 

DF[eval(parse(text=paste(m, quote(k)))),] 

DF[eval(parse(text=paste(m, "k"))),] 
相关问题