Command Line Subcommands in R Programming Language
Here’s the translation of the Go code to R, formatted in Markdown suitable for Hugo:
# Our first program will print the classic "hello world"
# message. Here's the full source code.
# In R, we don't need to import packages for basic printing
# or declare a main function. We can simply write our code
# at the top level.
print("hello world")
To run the program, save the code in a file named hello-world.R
and use the Rscript
command:
$ Rscript hello-world.R
[1] "hello world"
In R, we typically don’t compile our programs into binaries. Instead, we run R scripts directly or use them in an interactive R session.
To run the script in an interactive R session:
$ R
> source("hello-world.R")
[1] "hello world"
R also allows you to create packages, which are collections of R functions, data, and documentation. This is somewhat analogous to building binaries in other languages, as it allows you to distribute your code in a more structured way.
To create a simple package structure:
$ R
> library(devtools)
> create("helloworld")
This creates a new directory called “helloworld” with the basic structure of an R package. You can then add your R scripts to the R/
subdirectory of this package.
Now that we can run basic R programs, let’s learn more about the language.