DEV Community

Gabor Szabo
Gabor Szabo

Posted on • Updated on • Originally published at code-maven.com

Simple command-line counter with file storage in R

I have been learning R and preparing examples for R. One of the fun small script I created is also part of the counter example series.

filename = "count.txt"
count = 0

if (file.exists(filename)) {
    as.numeric(readLines(filename)) -> count
}

count <- count + 1

cat(count, end="\n")

fh <- file(filename, "w")
cat(count, end="\n", file = fh)
close(fh)
Enter fullscreen mode Exit fullscreen mode

After installing R we can run this script by typing in

Rscript counter.R
Enter fullscreen mode Exit fullscreen mode

In R there are at least 3 ways to assign a value to a variable. One can use the boring = sign as we have in the first two assignments.
We can also use the left arrow <- and we can also use the ->. In this script I used all 3, just to demo them. I think in a real script I'd stick to boring =, but as I can see code written by others, they also like to use the other signs.

The file.exists and the readLines functions seem to have very descriptive names.

The as.numeric function converts a string or "characters" as they are called in R to a number or "numeric" as it is referred to in R.

cat is a similar to print, but as I understand it is more generic function. Among other things it does not "number" the output lines. It also accepts various parameters such as the end parameter and the file parameter.

The file function with the w parameter opens the file for writing and returns a filehandle. We then use cat and direct its output to the file. At the end we close the file.

Top comments (1)

Collapse
 
sidunn profile image
Si Dunn

A good, helpful example for this R beginner. Thanks!