lohman
lohman

Reputation: 15

Calculate a given formula in a cell

I've received a .csv - file containing over 1000 observations. In there I can find a column with only formulas like for example shown in this test vector:

formula <- c("[(2+2)+(2+2)+(2+2)]", "[(1+1)+(2+2)+(3+3)+(1+1)]")

All given as characters. I now try to calculate each formula in this file. The results should be a numeric value: C (12, 14)

Should I do this with a separate() function, to have several new columns or is there any other easier solution with R? I want to have an R command, it is not useful for me to edit the column in the .csv- file directly.

Upvotes: 1

Views: 30

Answers (2)

IceCreamToucan
IceCreamToucan

Reputation: 28675

This format is very similar to the expected input for the package glue

library(glue)

sapply(xy, glue, .open = '[', .close = ']')

# [(2+2)+(2+2)+(2+2)] [(1+1)+(2+2)+(3+3)+(1+1)] 
#                "12"                      "14"

Upvotes: 0

Roman Luštrik
Roman Luštrik

Reputation: 70643

Maybe like this?

xy <- c("[(2+2)+(2+2)+(2+2)]", "[(1+1)+(2+2)+(3+3)+(1+1)]")
xy <- gsub("\\[|\\]", replacement = "", xy)

> sapply(xy, FUN = function(x) eval(parse(text = x)))
      (2+2)+(2+2)+(2+2) (1+1)+(2+2)+(3+3)+(1+1) 
                     12                      14

Upvotes: 3

Related Questions