Filtering Data Frame when filter column and filter value are variables

Hello

I am trying to learn how to use base R to filter a data frame to select rows where a certain column match a specific value, BUT for a case where the filter column and the filter value are held in variables.

So for example:

df <- data.frame(id = seq(1, 100, 1), value = floor(runif(100, 0, 10)))

filter_col <- "value"
filter_value <- 10

# how to filter using now only filter_col and filter_value?

#I tried things like this but could not get it to work:
df2 <- val <- subset(df, eval(filter_col) & eval(parse(text = filter_value)))

Any help appreciated!

I would do it like this:

df2 <- df[df[filter_col] == filter_value, ]

Note that setting filter_value to 10 returns zero rows because you used floor() to get the value column.

1 Like
set.seed(42)
d <- data.frame(id = seq(1, 100, 1), value = floor(runif(100, 0, 10)))

filter_col <- "value"
filter_value <- 2 # no 10s in value
d[which(d$value == filter_value),]
#>    id value
#> 3   3     2
#> 14 14     2
#> 38 38     2
#> 59 59     2
#> 67 67     2
#> 70 70     2
#> 73 73     2
#> 87 87     2
#> 93 93     2

Created on 2023-07-06 with reprex v2.0.2

2 Likes

Many thanks! This solution is what I was looking for.

Many thanks. This solution can also work for me, except you are assuming the column "value" is known in your use of d$value?

I set it equal to 2 after finding that 10 returned no rows, which I thought might be confusing.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.