【问题标题】:subset from a list of data.frames in RR中data.frames列表的子集
【发布时间】:2019-09-29 23:39:12
【问题描述】:

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

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

例如,如果用户想要对age == 2age == 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"))

【问题讨论】:

  • 你需要foo(d = 2:4, per = 1:2, extract =quote(age == 2), age = 1:3, prof = c("med", "low", "med"))和函数内部out1 &lt;- subset(out, subset = eval(extract))
  • 你能看看下面的解决方案吗

标签: r function subset


【解决方案1】:

我们可以在 '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"))

【讨论】:

  • @rnorouzian 用户能否将其作为字符串传递"age ==2"
【解决方案2】:

这不使用任何包,也没有明确使用eval

foo2 <- function(d, per, ..., extract = TRUE) {
  out <- data.frame(...)
  h <- split(out, rep(seq_along(per), per))
  s <- substitute(extract)
  lapply(h, function(x) do.call("subset", list(x, s)))
}


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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 1970-01-01
    • 2020-02-13
    • 2019-09-13
    • 1970-01-01
    • 2020-03-07
    相关资源
    最近更新 更多