Subsetting in a second level R function

孤街浪徒 提交于 2019-12-03 16:25:54

Instead of using lapply, here a for loop can be used

lst1 <- vector("list", length(G))
for(i in 1:3) lst1[[i]] <- foo2(data = D, by = G[[i]])

-checking

identical(lst1[[2]],  foo2(data = D, by = G[[2]]))
#[1] TRUE
identical(lst1[[3]],  foo2(data = D, by = G[[3]]))
#[1] TRUE

For the lapply part, there seems to be a conflict with i anonymous function which is also called in the G. If we use a new variable say 'j'

lst2 <- lapply(1:3, function(j) foo1(data = D, by = G[[j]]))

should work

identical(lst2[[2]], lst1[[2]])
#[1] TRUE

Your foo2 function tries to evaluate the expression

foo1(data = D, by = G[[i]])

but it doesn't have i available. You need to evaluate G[[i]] in the anonymous function you're passing to lapply to get an expression defining the subset, and then evaluate that subset in foo2. I recommend naming that function instead of using an anonymous one; it makes debugging a lot easier.

Here's some recoding that appears to work:

Redefine foo2 to

foo2 <- function(data, by){
  by <- eval(by, envir = data)
  foo1(data = data, by = by)
}

and

foo3 <- function(i) {
    expr <- G[[i]]
    foo2(data = D, by = expr)
}

and then

lapply(1:3, foo3)

I'm not sure this does exactly what you want, but it should be close enough that you can fix it up.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!