簡體   English   中英

R中data.frames列表的子集

[英]subset from a list of data.frames in R

在下面的函數中, ...表示用戶命名的任何矢量(例如, numericcharacter等)。 例如,用戶可以定義age = 1:3prof = c("med", "low", "med") 這些額外的矢量被添加到一個名為outdata.frame out

我想知道是否有辦法創建一個名為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"))

這不使用任何包,也不顯式使用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)

我們可以在'extract'中傳遞帶引號的表達式並eval以過濾行

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM