Starting with creating our data file data.txt:
12
54
7
332
54
1
0
As before we start with defining a variable count
to start at zero. We increase it by 1 each time around the loop and print it out at the end:
lines <- readLines(file("data.txt"))
total <- 0
count <- 0
for (line in lines){
number <- as.numeric(line)
total <- total + number
count <- count + 1
}
print(paste("Sum of all", count, "values is:", total))
Rscript file.R
[1] "Sum of all 7 values is: 460"