Home > Software design >  using paste0 within dplyr::filter function
using paste0 within dplyr::filter function

Time:12-15

I am having some trouble using paste0 within the dplyr::filter function and would appreciate some help. I have pasted the code below. When I run it my the result I am getting has 0 rows instead of 2.

sig_time_hours_results1 <- data.frame (ID  = c("value_1", "value_2", "value3", "value4"),
                  Pval_time_hours8h = c(1.00, 0.005, 0.006, 0.2)
                  )

hour = "8h" 
Pval_time_hours <- paste0("Pval_time_hours", hour)
sig_time_hours_results2 <- dplyr::filter(sig_time_hours_results1, paste0(Pval_time_hours) < 0.05)

CodePudding user response:

We could use .data with [[

dplyr::filter(sig_time_hours_results1, .data[[Pval_time_hours]] < 0.05)

-output

      ID Pval_time_hours8h
1 value_2             0.005
2  value3             0.006

CodePudding user response:

You need to be more careful when using strings as column names. You can't just use `paste0() to turn a string into a column name. One way to do this would be to use tidyseslectors. For example

sig_time_hours_results2 <- sig_time_hours_results1 |> 
    filter(if_all(Pval_time_hours, ~.x < 0.05))

Even though we are only checking one column, we still use if_all to make sure the filters hold.

  • Related