1

I am trying to load an equation from .txt file into an R function. The equations are very long but for sake of simplicity my test.txt file contains only a + b.

equation <- function(a,b) {
data <- read.delim("test.txt", header = F, col.names="equation", strip.white=F)
return (data$equation) 
}

equation(1,1)

I have tried the code above which should give the result of 2 (1+1) but the data is loaded as factor and I cannot crack how to parse it as attributes.

zx8754
  • 52,746
  • 12
  • 114
  • 209
pythonista
  • 23
  • 5
  • 1
    What do you mean by “parse it as attributes”? As far as I can tell your code works, although the entire function could be replaced by just `readLines('test.txt')`. – Konrad Rudolph Sep 23 '20 at 09:56
  • At the moment it returns "[1] a + b" instead of numeric answer. – pythonista Sep 23 '20 at 11:34

2 Answers2

2

Using readLines.

eq <- function(a, b) eval(parse(text=readLines("equ.txt")))
eq(1, 1)
# [1] 2
jay.sf
  • 60,139
  • 8
  • 53
  • 110
1

Use eval(parse()):

equation <- function(a,b) {
    data <- readr::read_file("test.txt")
    return( eval(parse(text = data) ))
}
equation(4,5)
[1] 9
xwhitelight
  • 1,569
  • 1
  • 10
  • 19