There is a very similar question here: How to select columns based on grep in dplyr::tibble
However I think that the select_if
was superseeded with select(where())
.
I know that I can do the following and it works:
# select all columns with three characters
mtcars %>%
select(
matches("^[a-zA-Z]{3}$")
)
But I can also use an anonymus function (here over all the column values and not the names) to select columns.
mtcars %>%
select(
where(function(x)sum(is.na(x)) == 0)
)
So I thought I could use an anonymus function and grepl
to select columns. And this does not work:
mtcars %>%
select(
where(
function(x) grepl("^[a-zA-Z]{3}$", x)
)
)
How could I make this work? I mean I could always use the matches
helper. But I would just like to understand how to use
select(where())
statement over the names of the dataframe and not over all the values in a column.
Update
This works:
mtcars %>%
select(
which(grepl("^[a-zA-Z]{3}$", names(.)))
)
But I am not sure if there isn't a better way;)