Object not found error when using rlang::parse_expr

I'm wondering if someone can point out why this simple example doesn't work.

I think it's something to do with the fact that I'm using the !! operator?

But been unable to figure out what I'm doing wrong.

I want to get the number of rows from the starwars dataset where the condition in x$value is satisfied.

I run into the error Error in is_character(x) : object '.x' not found.

library(dplyr)
library(purrr)
library(rlang)

x <- tibble(
  value = c("skin_color == 'fair'")
)

x %>% 
  mutate(nrows = map_dbl(
    value,
    ~ {
      starwars %>% 
        filter(!!parse_expr(.x)) %>% 
        nrow()
    }
  ))

The reason for your error is that you need a dot (.) instead of .x inside parse_expr to pass the value via magrittr pipe. However, this does not work for other reasons. I don't think you can use map_dbl here. I've re-written the code by creating a separate function. It is easier to read and it works:

library(dplyr)
library(purrr)
library(rlang)

x <- tibble(
  value = c("skin_color == 'fair'", "eye_color == 'blue'")
)

star_rows <- function(v) {
  starwars |>
    filter(!!parse_expr(v)) |>
    nrow()
}

x |> 
  rowwise() |> 
  mutate(nrows = star_rows(value))

rowwise is needed because star_rows() is not vectorised.

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.