0

I'm trying to add solutions of a formula to a data frame using dplyr. With the function mutate() I want to create a column called cutoff. The rows in the column cutoff should contain the solution of the formula stored in a2.

Here is my code:

library(dplyr)

a1 <- "AVG(C1) * .290"
a2 <- gsub("AVG[(]C1[)]","mean",a1)


newiris <- iris %>%
group_by(Species) %>%
summarize(n= n(),mean = mean(Petal.Width), 
cv=sd(Petal.Width)/mean(Petal.Width)*100) %>%
mutate(cutoff=a2)

This is want I get in the moment:

enter image description here

This is what I want:

enter image description here

Any help would be appreciated.

Lisminjul
  • 83
  • 4
  • 1
    I think you're trying to look for `eval(parse(text = ))` see [this SO answer](https://stackoverflow.com/questions/1743698/evaluate-expression-given-as-a-string) – EJJ Feb 27 '19 at 14:45
  • Ugh. `fortunes::fortune(106)`. This seems like an [XY problem](http://xyproblem.info/). Why are you trying to do a calculation stored in a string? – Gregor Thomas Feb 27 '19 at 14:50
  • This is just an example I created because I couldn't find the solution for my actual code. In my actual code the formula is typed in a textInput in shiny. I have to transfer the input to the mutate function. That's why I created an example with a calculation stored in a string. – Lisminjul Feb 27 '19 at 15:04

2 Answers2

1
newiris <- iris %>%
  group_by(Species) %>%
  summarize(n = n(), mean = mean(Petal.Width), 
            cv = sd(Petal.Width)/mean(Petal.Width)*100) %>%
  mutate(cutoff = eval(parse(text = a2)))
EJJ
  • 1,474
  • 10
  • 17
0

Using some fancy quotation we can do this rather easily:

library(tidyverse)

a1 <- "AVG(C1) * .290"
a2 <- gsub("AVG[(]C1[)]","mean",a1)
a3 <- paste("cutoff =", a2)


newiris <- iris %>%
  group_by(Species) %>%
  summarize(n = n(),
            mean = mean(Petal.Width), 
            cv= sd(Petal.Width) / mean(Petal.Width)*100) %>%
  mutate(!!rlang::parse_expr(a3))

Created on 2019-02-27 by the reprex package (v0.2.1)

dylanjm
  • 2,011
  • 9
  • 21