在辅助R函数中使用`subset()`

时间:2019-06-23 20:32:56

标签: r list function dataframe subset

在请求时,函数foo1可以subset列表by所需的变量(例如by = ESL == 1)。否则,foo1只会简单地输出输入列表本身。

出于我的目的,我需要在名为foo1的新函数中使用foo2我想知道foo2为何失败以及如何解决:

Error in eval(e, x, parent.frame()) : object 'ESL' not found

完整的可复制数据和代码如下:

foo1 <- function(by, data){

L <- split(data, data$study.name) ; L[[1]] <- NULL

 if(!missing(by)){

 s <- substitute(by)    

 H <- lapply(L, function(x) do.call("subset", list(x, s)))

 L <- Filter(nrow, H)
   }
return(L)
}

## EXAMPLE OF USE:
D <- read.csv("https://raw.githubusercontent.com/izeh/i/master/k.csv", h = T) ## Data

foo1(data = D, by = ESL == 1) ## works fine :-) @@@@

## BUT:
foo2 <- function(by, data){

  foo1(by = by, data = data)
}

## EXAMPLE OF USE:
foo2(data = D, by = ESL == 1) ## Fails :-( @@@@

1 个答案:

答案 0 :(得分:1)

在这里,我们可以将foo2修改为eval来完善函数调用

foo2 <- function(by, data){ 

  eval(substitute(foo1(by = by, data = data)))
 }

out1 <- foo1(data = D, by = ESL == 1) 
out2 <- foo2(data = D, by = ESL == 1) 
identical(out1, out2)
#[1] TRUE