Starting with our data file, calc.txt
:
4 * 6
5 + 6
457 - 75
54 / 3
4 + 6
calc.R
then looks like:
lines <- readLines(file("calc.txt"))
for (line in lines){
words <- strsplit(line, " ")[[1]]
lhs <- as.numeric(words[1])
operator <- words[2]
rhs <- as.numeric(words[3])
if (operator == "+"){
cat(line, "is", lhs + rhs, "\n")
} else if (operator == "-"){
cat(line, "is", lhs - rhs, "\n")
} else if (operator == "*"){
cat(line, "is", lhs * rhs, "\n")
} else if (operator == "/"){
cat(line, "is", lhs / rhs, "\n")
}
}
Rscript calc.R
4 * 6 is 24
5 + 6 is 11
457 - 75 is 382
54 / 3 is 18
4 + 6 is 10