有没有一种简单的方法可以从数据框中的列中选择特定的观察值以供函数使用?像 excel 枢轴 table 中的过滤器?

Is there an easy way to pick specific observations from column out of a data frame for a function to use? Like a filter in excel pivot table?

下面我有一个函数从封装gapminder到运行分析一下。我需要从可用的五个大洲中选出两个。

library(gapminder)

part3 <- gapminder
continent1 <- subset(part3, continent == "Asia")
continent2 <- subset(part3, continent =="Africa")
#As I'm going to t-test I need two factors - picking two continents
part3c <- rbind(continent1, continent1)

问题有没有办法让用户选择大陆进行分析,例如,一些代码说“从五个可用的中选择两个”,允许分析运行 有不同的组合?

类似于从 excel 枢轴 table 中过滤数据获取输出,或者我是否需要每次都在大洲中编码 - 如上所述?

你想要这样的东西吗?
Function combn returns 一个向量的组合,在下面的例子中是 2 x 2 并且对它们中的每一个应用一个函数。函数 test_fun 首先确保组的大小相同,然后运行 ​​t 检验。

在示例调用中,我按大陆测试 lifeExp 的相等性,但可以测试任何其他列。

test_fun <- function(X, col){
  cols <- c(col, "continent")
  n <- min(nrow(X[[1]]), nrow(X[[2]]))
  Y <- lapply(X, \(y) {
    if(nrow(y) > n)
      y[sample(nrow(y), n), cols]
    else y[cols]
  })
  Y <- do.call(rbind, Y)
  t.test(get(col) ~ continent, Y)
  
}

sp_part3 <- split(part3, part3$continent)

combn(sp_part3, 2, test_fun, simplify = FALSE, col = "lifeExp")