在第二级R功能中的子集 [英] Subsetting in a second level R function

查看:105
本文介绍了在第二级R功能中的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

函数foo1可以通过请求的变量(例如,by = type == 1)对列表进行子集化.否则,foo1只会简单地输出输入列表本身.

Function foo1 can subset a list by a requested variable (e.g., by = type == 1). Otherwise, foo1 will simply output the inputted list itself.

出于我的目的,我需要在名为foo2的新函数中使用foo1.

For my purposes, I need to use foo1 within a new function called foo2.

在下面的代码中,我想要的输出是这样获得的:foo2(data = D, by = G[[1]]) ; foo2(data = D, by = G[[2]]) ; foo2(data = D, by = G[[3]]).

In my code below, my desired output is obtained like so: foo2(data = D, by = G[[1]]) ; foo2(data = D, by = G[[2]]) ; foo2(data = D, by = G[[3]]).

但是,我想知道为什么当我使用lapply循环遍历G时,出现如下所示的错误 ?

But, I wonder why when I loop over G using lapply, I get an error as shown below?

foo1 <- function(data, by){

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

  if(!missing(by)){

   L <- lapply(L, function(x) do.call("subset", list(x, by)))
  }
 return(L)
}


foo2 <- function(data, by){

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

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

G <- lapply(unique(na.omit(D$type)), function(i) bquote(type == .(i)))# all levels of `type`

foo2(data = D, by = G[[1]]) # Works fine without `lapply` :-)

lapply(1:3, function(i) foo2(data = D, by = G[[i]])) # Doesn't work with `lapply`! :-(
# Error in do.call("subset", list(x, by)) : object 'i' not found

推荐答案

代替使用lapply,这里可以使用for循环

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]])

-检查

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


对于lapply部分,似乎与i匿名函数存在冲突,该匿名函数也在G中被调用.如果我们使用新变量,请说"j"


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]]))

应该工作

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

这篇关于在第二级R功能中的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆