Starting with creating our data file data.txt:
12
54
7
332
54
1
0
We start by defining an integer, total
to be zero before the loop. Inside the loop we add the line of code total <- total + number
which increases the variable total
by the value in the variable number
. Finally we print the total:
lines <- readLines(file("data.txt"))
total <- 0
for (line in lines){
number <- as.numeric(line)
total <- total + number
}
print(paste("Sum of all values is:", total))
Rscript file.R
[1] "Sum of all values is: 460"