[R] combine filter() and select()

Hadley Wickham h@w|ckh@m @end|ng |rom gm@||@com
Thu Aug 20 18:52:44 CEST 2020


On Wed, Aug 19, 2020 at 10:03 AM Ivan Calandra <calandra using rgzm.de> wrote:
>
> Dear useRs,
>
> I'm new to the tidyverse world and I need some help on basic things.
>
> I have the following tibble:
> mytbl <- structure(list(files = c("a", "b", "c", "d", "e", "f"), prop =
> 1:6), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))
>
> I want to subset the rows with "a" in the column "files", and keep only
> that column.
>
> So I did:
> myfile <- mytbl %>%
>   filter(grepl("a", files)) %>%
>   select(files)
>
> It works, but I believe there must be an easier way to combine filter()
> and select(), right?

Not in the tidyverse. As others have mentioned, both [ and subset() in
base R allow you to simultaneously subset rows and columns, but
there's no single verb in the tidyverse that does both. This is
somewhat informed by the observation that in data frames, unlike
matrices, rows and columns are not exchangeable, and you typically
want to express subsetting in rather different ways.

Hadley

-- 
http://hadley.nz



More information about the R-help mailing list