Start by deleting all the lines inside the file data.txt
.
We then edit the end of the script where it calculates the mean so that it only runs if the count is greater than zero:
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))
if (count > 0){
print(paste("The mean is", mean))
}
Rscript file.R
[1] "Sum of all 0 values is: 0"