I'm trying to define a function that uses dplyr::select
to select a column that has the same name in multiple dataframes, so the column's name shouldn't be a relevant input to the user. For instance, I'd like something like this to work for any data frame that has the "Sepal.Length" column inside of it:
sel_Sepal.Length <- function(df) {
# The code we are looking for...
}
So that I can apply it
sel_Sepal.Length(iris)
To obtain a result like this:
Sepal.Length
1 5.1
2 4.9
3 4.7
4 4.6
5 5.5
... ...
I'm aware of this answer for a similar problem. But the difference is that, I'd like the function to work without inputting the column's name, which should be fixed inside the function's code.
This could possibly be considered a trivial question, since one can make the user input the column's name and make it work:
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
... ...
But I think there's a concept I'm missing so I can't make it work the way I asked (without inputting the column to be selected). This is a question asked just for the sake of finding that missing concept. Hope it could help others. Thank you in advance!