R中data.frames列表的子集

诺鲁齐安

在我的函数如下...表示任何载体(例如,numericcharacter等等)命名的用户。例如,用户可以定义age = 1:3prof = c("med", "low", "med")这些额外的向量会添加到data.frame被称为中out

我想知道是否有一种方法可以创建一个新的参数,称为extract允许用户从最终输出中子集化h

例如,如果用户想对它进行子集设置,age == 2或者age == 2 & prof == "low"使用extract = age == 2 & prof == "low"返回来自输出的相应匹配项

foo <- function(d, per, ...){ ## Add a new argument called `extract`

 out <- data.frame(d, ...)

h <- split(out, rep(seq_along(per), per))  ## `extract` should subset from `h`
return(h)
}
# Example of use:
foo(d = 2:4, per = 1:2, age = 1:3, prof = c("med", "low", "med"))
阿克伦

我们可以在'extract'中传递带引号的表达式,然后通过evaluate过滤行

library(tidyverse)
foo <- function(d, per, extract, ...){ ## Add a new argument called `extract`

   extract <- rlang::enexpr(extract)
   out <- data.frame(d, ...)


  h <- split(out, rep(seq_along(per), per))  
  map(h, ~ .x %>% 
            filter(!! extract))

 }

foo(d = 2:4, per = 1:2, extract = age == 2, age = 1:3, prof = c("med", "low", "med"))
#$`1`
#[1] d    age  prof
#<0 rows> (or 0-length row.names)

#$`2`
#  d age prof
#1 3   2  low

或使用 base R

foo <- function(d, per, extract, ...){ ## Add a new argument called `extract`

   extract <- substitute(extract)
   out <- data.frame(d, ...)


   h <- split(out, rep(seq_along(per), per))  
   lapply(h, function(x) subset(x, subset = eval(extract)))

}

foo(d = 2:4, per = 1:2, extract = age == 2, age = 1:3, prof = c("med", "low", "med"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章