Home > Net >  Unexpected results using eval() in R
Unexpected results using eval() in R

Time:10-15

I have a column called "equation" which stored formuala about "t". Another column is "t". I want to calculate the equation's value (y) according to each t in the row. Below is an example.

library(magrittr);library(dplyr)

dt <- data.frame(t = c(1,2,3),
                 equation = c("t 1", "5*t", "t^3"))

dt %<>% 
  mutate(y = eval(parse(text = equation)))

However, the results seem not expected:

  t equation  y
  1      t 1  1
  2      5*t  8
  3      t^3 27

The expected results for y is: 2, 10, 27. What should I do to fix it (but the third y is correct)?

CodePudding user response:

This is because eval(parse()) isn't vectorised. You can get around this using rowwise():

library(magrittr)
library(dplyr, warn.conflicts = FALSE)

dt <- data.frame(
  t = c(1,2,3),
  equation = c("t 1", "5*t", "t^3")
)

dt %<>% 
  rowwise() %>%
  mutate(y = eval(parse(text = equation))) %>%
  ungroup()
#> # A tibble: 3 × 3
#>       t equation     y
#>   <dbl> <chr>    <dbl>
#> 1     1 t 1          2
#> 2     2 5*t         10
#> 3     3 t^3         27

Created on 2022-10-14 with reprex v2.0.2

  •  Tags:  
  • r
  • Related