bill999
bill999

Reputation: 2540

How to use base R function using data subsetted with tidyverse

Say I have these data:

testdata <- data.frame(a=c(1,2,3), b=c("a", "b", "b"))

I want to use the base R table command to get a tally of the variable b, but after subsetting based on a's values. Importantly, I want to subset using tidyverse in one line. Here is an attempt that doesn't work; I am not sure how to get it to correctly refer to column b.

table(testdata %>% filter(a<3) $ b)

Note this is how I would do it in two steps:

testdata2 <- testdata %>% filter(a<3)
table(testdata2$b)

Upvotes: 1

Views: 100

Answers (1)

akrun
akrun

Reputation: 887871

Use pull to extract the column and then apply the table

library(dplyr)
testdata %>% 
     filter(a<3) %>%
     pull(b) %>% 
     table

-output

a b 
1 1 

Or use base R with |> operator (from R 4.1.0 onwards)

subset(testdata, a < 3, select = b) |> 
      table()

a b 
1 1 

As we are already using dplyr, why not use count

testdata %>%
    filter(a < 3) %>%
    count(b)

Upvotes: 2

Related Questions