Why is the filter function not working in R if a variable is used?

Viewed 159

I want to create a subset of a dataframe by filtering. With my code, no rows are filtered (plotdata has 3 rows), unless I change the last "chip_id" variable to 434.

What am I missing?

name value chip_id
a 3 244
b 4 434
c 5 532
chip_id <- 434
analyzed_data <- read.csv("./test.csv",
                      #colClasses = c("chip_id"="factor", )
)
plotdata <- analyzed_data %>% filter(chip_id == chip_id)
1 Answers

It is all about NSE (non-standard evaluation) it can work if you unquoting your global environment variable ,

library(dplyr , warn.conflicts = FALSE)

analyzed_data <- data.frame(name = c("a" , "b" , "c") , 
                            value = c(3,4,5) , 
                            chip_id = c(244 , 434 , 532))
analyzed_data

#>   name value chip_id
#> 1    a     3     244
#> 2    b     4     434
#> 3    c     5     532

chip_id <- 434

plotdata <- analyzed_data %>% filter(chip_id == !!chip_id)

plotdata

#>   name value chip_id
#> 1    b     4     434

Created on 2022-05-30 by the reprex package (v2.0.1)

Related