在函数中使用 dplyr::select 来 select 来自多个数据帧的固定列

Using dplyr::select within a function to select a fixed colum from multiple data frames

我正在尝试定义一个函数,该函数使用 dplyr::select 到 select 在多个数据框中具有相同名称的列,因此该列的名称不应是相关输入用户。例如,我希望这样的东西适用于其中包含 "Sepal.Length" 列的任何数据框:

sel_Sepal.Length <- function(df) {
        # The code we are looking for...
}

以便我可以应用它

sel_Sepal.Length(iris)

要获得这样的结果:

    Sepal.Length
1            5.1
2            4.9
3            4.7
4            4.6
5            5.5
...          ...

我知道这个 有类似的问题。但不同的是,我希望函数在不输入列名的情况下工作,列名应该在函数代码中固定。

这可能被认为是一个微不足道的问题,因为可以让用户输入列的名称并使其工作:

selectvar <- function(df, var) {
        var <- enquo(var)
        df %>%
                select(!!var)
}

selectvar(iris, Sepal.Length)

    Sepal.Length
1            5.1
2            4.9
3            4.7
4            4.6
5            5.5
...          ...

但我认为我缺少一个概念,所以我无法按照我要求的方式工作(不输入要 selected 的列)。提出这个问题只是为了找到那个缺失的概念。希望它可以帮助别人。提前致谢!

我可能误解了你的问题;因为您明确希望在函数内对列名进行硬编码(至少这是我从 "I'd like the function to work without inputting the column's name, which should be fixed inside the function's code" 推断的),您可以

sel_Sepal.Length <- function(df) {
    df %>% select(Sepal.Length)
}

但这意味着整个功能真的没有太多意义

也许你可以澄清一下整个练习的要点?