【问题标题】:Using `subset()` within a secondary R function在辅助 R 函数中使用 `subset()`
【发布时间】:2019-11-05 17:27:16
【问题描述】:

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

出于我的目的,我需要在一个名为 foo2 的新函数中使用 foo1。 但是我想知道为什么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 :-( @@@@

【问题讨论】:

  • 怎么会失败?
  • 这是环境问题
  • @akrun,我明白了,但有什么替代方案?
  • 在foo2,试试eval(substitute(fool1, by = by, data = data)))

标签: r list function dataframe subset


【解决方案1】:

这里,我们可以修改foo2为evalluate函数调用

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-17
    • 2015-08-13
    • 1970-01-01
    • 2016-04-25
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多