我想基于变量创建数据框架子集。我可以使用eval和expression为1变量执行此操作,但找不到适用于2个或更多条件的示例。
set.seed(1)
df<-data.frame(N=letters[1:10],y=runif(10)*3)
df$M<-ceiling(df$y)
# N=b & M=2 are my "dynamic" conditions:
N<-"b"
M<-2
subex<-cat("N==\"",N,"\" & M==",M,"",sep="")
# gives: N=="b" & M==2
sdf<-subset(df,eval(expression(subex)),) # --> error
# Error in subset.data.frame(df, eval(expression(subex)), ) :
# 'subset' must be boolean
# the code itself works
sdf2<-subset(df,N=="b" & M==2,)
# gives desired result:
# N y M
# 2 b 1.116372 2