MonkeyCousin
MonkeyCousin

Reputation: 189

How can I use a pre-assigned variable in dplyr::filter?

When I assign expt as below, I get a tibble of dim 175, 81:

expt <- 5
mydata <- loaded_data %>% filter(expt == expt) %>%
  select(leaf.TN.pc | starts_with("air_")) %>%
  drop_na(leaf.TN.pc)

This is not what I want. Instead if I assign expt inline, as:

mydata <- loaded_data %>% filter(expt == expt) %>%

I get what I want, which is only obs from experiment 5, dim = 79, 81.

Upvotes: 0

Views: 136

Answers (1)

Piotr K
Piotr K

Reputation: 1025

What you did was comparing expt column with itself which was always true. Below the solution that will work for either one chosen value (expt_chosen <- 1) or multiple values (expt_chosen <- c(1, 3)). Just use %in% operator.

library(tidyverse)

expt_chosen <- c(1, 3)

dframe <- data.frame(name = letters[1:5], expt = 1:5)
dframe
#>   name expt
#> 1    a    1
#> 2    b    2
#> 3    c    3
#> 4    d    4
#> 5    e    5

dframe %>% filter(expt %in% expt_chosen)
#>   name expt
#> 1    a    1
#> 2    c    3

Created on 2020-05-14 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions