Starting with creating our data file data.txt:
12
54
7
332
54
1
0
Here the loop itself has not changed, we’ve just created a new variable afterwards, mean
which is calculated from total
and count
:
lines <- readLines(file("data.txt"))
total <- 0
count <- 0
for (line in lines){
number <- as.numeric(line)
total <- total + number
count <- count + 1
}
mean <- total / count
print(paste("Sum of all", count, "values is:", total))
print(paste("The mean is", mean))
Rscript file.R
[1] "Sum of all 7 values is: 460"
[1] "The mean is 65.7142857142857"