Evaluale strings as expression in mutate

Hi

I'd like to row-wise evaluate expressions stored as strings in a data.frame. Is there a way to correct the code below so that y is created by the string evaluation using the parameters a and b on the same row?

Thanks in advance

PS: note that this reprex is somewhat sanitize. In my actual workflow, the content of the 'x' column is unknown a priori and string evaluations may lead to errors or objects that are not numeric, so some error trapping would be needed.

require(dplyr)
df <- data.frame(
  a = 1:5,
  b = 2:6,
  x = c(NA, 'sin(a)', NA, 'log(b)', NA)
) %>%
  mutate(
    y = eval(parse(text = x)),
    y_expected = c(NA, sin(2), NA, log(5), NA)
  )

I suppose this is 'ugly' but it works.

library(dplyr)
library(rlang)

myfunc <- function(x,cd){
  p <- parse(text=x)
  eval(p,envir = cd)
  }
df <- data.frame(
  a = 1:5,
  b = 2:6,
  x = c(NA, 'sin(a)', NA, 'log(b)', NA)
) %>% rowwise() %>%
  mutate(
    y=myfunc(x, pick(everything()))
  ) %>% ungroup()

Thanks @nirgrahamuk for the pointer.

Since pick is only available since dplyr 1.1.0, I am wondering if one alternative could be

library(dplyr)
library(rlang)

myfunc <- function(x,cd){
  p <- parse(text=x)
  eval(p,envir = cd)
  }
df <- data.frame(
  a = 1:5,
  b = 2:6,
  x = c(NA, 'sin(a)', NA, 'log(b)', NA)
) %>% rowwise() %>%
  mutate(
    y=myfunc(x, across())
  ) %>% ungroup()

Alternative is cur_data_all()
I swapped it for pick to avoid the modern warning

This topic was automatically closed 21 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.