Skip to main content

Hello World (first programs) · Beginner · 14 min

Hello World in R: Rscript, vectors and your first function

By Padding · Updated 18 Nov 2026
R 4.6.2 · r-base:4.6.2

You will install R 4.6, run Hello World in the console and as a script with Rscript, see why every result starts with [1], and write a greet function that takes names from the command line.

On this page

R is a language made by statisticians for working with data. Its basic unit is not a single number or a single piece of text but a vector: an ordered list of values of one type. A lone number in R is a vector of length one. That one design choice explains the [1] you see in front of almost every result, and it is why R can add 2 to a thousand values without you writing a loop.

In this tutorial you install R 4.6, print Hello World in the R console, save a script and run it with Rscript, and look closely at vectors. Then you go one step further: you write a greet function, give it names from the command line, and learn when to use print, cat and paste.

R is used for statistics, data analysis and charts in universities, public health, banking, market research and bioinformatics, where it is a standard tool for analysing genetic data. Most of that work builds on packages from CRAN, the Comprehensive R Archive Network. R grew out of the S language from Bell Labs, and a new minor version (4.5, 4.6 and so on) arrives each spring.

Step 1 · Install R 4.6

R itself is all you need here. RStudio and Positron are popular editors for R, and you may want one later, but every step below works with a terminal and a plain text editor.

  • Ubuntu: Ubuntu's own r-base package can lag behind the current release, so add CRAN's Ubuntu repository, which carries R 4.6 for Ubuntu 26.04, 24.04 and 22.04:
Bash
sudo apt update
sudo apt install --no-install-recommends software-properties-common dirmngr
wget -qO- https://cloud.r-project.org/bin/linux/ubuntu/marutter_pubkey.asc | sudo tee -a /etc/apt/trusted.gpg.d/cran_ubuntu_key.asc
sudo add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran40/"
sudo apt install --no-install-recommends r-base

The third line downloads the key that CRAN signs its packages with, so apt can check they have not been tampered with. The fourth adds the repository for your Ubuntu release; $(lsb_release -cs) fills in its code name, such as resolute. The cran40 in the name is historical and still gives you R 4.6.

  • macOS: download the R 4.6.2 .pkg for your Mac's chip (Apple silicon or Intel) from cran.r-project.org, under "Download R for macOS", and run it.
  • Windows: download "base" R from cran.r-project.org, under "Download R for Windows", and run the installer. If Rscript is not found in a new terminal afterwards, add R's bin folder (for example C:\Program Files\R\R-4.6.2\bin) to your PATH, the list of folders the terminal searches for programs.

Now check the version:

Bash
R --version

Check it worked

The first line reads something like R version 4.6.2 (2026-10-29) -- "Diversified Portfolio", followed by copyright and licence lines. If it shows R version 4.3 or another older number, apt installed Ubuntu's own package: check that the add-apt-repository line ran without errors, then run sudo apt update and the install line again.

Step 2 · Say hello in the R console

Start the R console:

Bash
R

R prints a welcome message and a > prompt. Type each line after the > and press Enter:

Text
> print("Hello, World!")
[1] "Hello, World!"
> "Hello, World!"
[1] "Hello, World!"
> 6 * 7
[1] 42
  • print("Hello, World!") calls the print function with one piece of text. In R, text is called a character string and goes in double or single quotes.
  • Typing a value on its own also prints it. The console shows the result of every line you type, unless you store it somewhere.
  • 6 * 7 works the same way: R works out the answer and shows it.

Every result starts with [1]. You find out why in a later step; for now, read it as "this line starts at item 1".

Leave the console with q(). R asks Save workspace image? [y/n/c]:. Type n and press Enter. Saying y writes your variables to a hidden .RData file that loads silently next time, which confuses more beginners than it helps.

Check it worked

print("Hello, World!") shows [1] "Hello, World!", quotes included, and 6 * 7 shows [1] 42. After q() and n, your normal terminal prompt is back.

Step 3 · Save hello.R and run it with Rscript

Make a folder for this tutorial and create hello.R in it. On macOS or Linux you can paste the whole block into the terminal; on Windows, create the file in your editor with the three lines between the R markers.

Bash
mkdir -p ~/hello-r-demo
cd ~/hello-r-demo
cat > hello.R <<'R'
# hello.R: my first R script
greeting <- "Hello, World!"
print(greeting)
R
Rscript hello.R

Line by line:

  • # hello.R: my first R script is a comment. R ignores everything from # to the end of the line.
  • greeting <- "Hello, World!" stores the text in a variable called greeting. The arrow <- is R's assignment operator: read it as "gets". = also works for this, but <- is the convention in almost all R code you will read.
  • print(greeting) prints the value stored in greeting.
  • Rscript hello.R runs the file from top to bottom without opening the console, and exits when it reaches the end. R script files end in .R by convention.

Check it worked

The terminal prints [1] "Hello, World!" and returns to the prompt. ls in the folder shows hello.R.

Step 4 · See why output starts with [1]

Create vectors.R, which keeps three amounts you spent this week, in your own currency:

Bash
cat > vectors.R <<'R'
spend <- c(1200, 450, 3000)
print(spend)
print(length(spend))
print(spend[1])
print(spend * 2)
print(sum(spend))
print(length("Hello, World!"))
print(nchar("Hello, World!"))
print(1:30)
R
Rscript vectors.R

Line by line:

  • c(1200, 450, 3000) combines three numbers into one vector. c stands for combine.
  • print(spend) shows all three values on one line: [1] 1200 450 3000. R lines the numbers up in columns of equal width.
  • length(spend) is 3, the number of items.
  • spend[1] is 1200. R counts from 1, so the first item is [1]. Many other languages, including Python and JavaScript, count from 0.
  • spend * 2 doubles every item at once and prints [1] 2400 900 6000. Arithmetic on a vector applies to each item; R calls this vectorisation, and it is why R code for data has so few loops.
  • sum(spend) adds the items and gives 4650.
  • length("Hello, World!") is 1, not 13. The string is a character vector with one item in it. To count the characters inside it, use nchar, which gives 13.
  • 1:30 is the numbers 1 to 30. They do not fit on one line, so R wraps them, and the second line starts with the position of its first item, something like [26].

So [1] is not part of the value. It is a position label: "the first item on this line is item number 1". Even 42 was a vector, one item long.

Check it worked

You see nine results. spend * 2 shows [1] 2400 900 6000, length("Hello, World!") shows [1] 1 while nchar shows [1] 13, and the last result takes two lines, each starting with a number in square brackets.

Step 5 · Write a greet function that takes names

Now go one step further. Create greet.R, which defines a function and reads names typed after the script's name:

Bash
cat > greet.R <<'R'
greet <- function(name) {
  paste0("Hello, ", name, "!")
}

names_given <- commandArgs(trailingOnly = TRUE)

if (length(names_given) == 0) {
  names_given <- "World"
}

writeLines(greet(names_given))
R
Rscript greet.R
Rscript greet.R Ada
Rscript greet.R Ada Kofi "Ngozi Okafor"

Line by line:

  • greet <- function(name) { ... } creates a function and stores it in greet, using the same <- as any other value. In R a function is a value like a number or a string.
  • paste0("Hello, ", name, "!") joins its pieces into one string with nothing between them. A function returns the value of its last line, so there is no return needed.
  • commandArgs(trailingOnly = TRUE) returns the words typed after the script's name, as a character vector. Without trailingOnly = TRUE you also get the R program's own path and settings, which you rarely want.
  • if (length(names_given) == 0) checks whether no names were given; if so, the script falls back to "World".
  • writeLines(greet(names_given)) prints each string on its own line, without [1] or quotes.

Notice that greet contains no loop, yet it greets three people. paste0 is vectorised: given a vector of three names, it returns a vector of three greetings. This is the vector idea from the previous step at work.

Quotes around "Ngozi Okafor" keep the full name together as one word; without them the terminal passes Ngozi and Okafor as two names. Names with accents or tone marks, such as Adébáyọ̀, work too in a terminal that uses UTF-8, which modern Ubuntu, macOS and Windows Terminal do.

Check it worked

The three runs print Hello, World!, then Hello, Ada!, then three lines ending with Hello, Ngozi Okafor!.

Step 6 · Choose between print, cat and paste

R has three functions that beginners mix up. print shows a value the way the console does, cat writes plain text, and paste builds a string without showing anything. Create compare.R:

Bash
cat > compare.R <<'R'
name <- "Amara"
message_text <- paste("Hello,", name)
print(message_text)
cat(message_text, "\n")
cat("Total spent:", sum(c(1200, 450, 3000)), "\n")
print(paste0("ID-", 1:3))
R
Rscript compare.R

Line by line:

  • paste("Hello,", name) joins its pieces with a space between them and returns "Hello, Amara". Storing it with <- prints nothing: building a string and showing it are separate jobs.
  • print(message_text) shows [1] "Hello, Amara", with the position label and quotes. Use it to inspect what a value really is.
  • cat(message_text, "\n") writes Hello, Amara with no label and no quotes. cat does not end the line by itself, so "\n", the new line character, is added at the end. cat puts a space between each item it writes.
  • cat("Total spent:", sum(...), "\n") mixes text and a number in one line of output: Total spent: 4650.
  • paste0("ID-", 1:3) uses paste0, which joins with no space, and returns three strings, "ID-1" "ID-2" "ID-3", one for each number.

A rule of thumb: use paste or paste0 to build text, cat or writeLines to show text to people, and print to check values while you work.

Check it worked

You see four lines: [1] "Hello, Amara", then Hello, Amara without quotes, then Total spent: 4650, then [1] "ID-1" "ID-2" "ID-3".

Step 7 · Know how CRAN packages are installed

Much of R's value is in packages. You install one once per computer with install.packages, then load it in each script with library. You do not need a package for this tutorial; this is what it looks like, using jsonlite, a package for reading and writing JSON:

Text
install.packages("jsonlite")
library(jsonlite)
toJSON(list(name = "Ada", spend = c(1200, 450)))
  • install.packages("jsonlite") downloads the package from a CRAN mirror, a copy of CRAN on a server near you, and installs it into your R library folder. The name goes in quotes.
  • library(jsonlite) loads it, without quotes. You run this at the top of every script that uses the package.

On Windows and macOS, CRAN supplies ready-built packages, so installs are quick. On Linux, install.packages usually downloads source code and compiles it, which takes longer and may need extra system libraries; on prepaid mobile data, check a package's size on its CRAN page before installing a large one with many dependencies.

Check it worked

There is nothing to run in this step. You can say which call downloads a package (install.packages, once) and which loads it (library, in every script), and which of the two takes the name in quotes.

Step 8 · Fix the errors beginners hit

R cannot find the script. Rscript looks for the file in the folder your terminal is in. Run it from your home folder instead of the practice folder:

Bash
cd ~
Rscript hello.R

R stops with something like Fatal error: cannot open file 'hello.R': No such file or directory. Go back with cd ~/hello-r-demo, or give the full path, Rscript ~/hello-r-demo/hello.R.

Capital letters matter. R is case-sensitive, so Print is not print:

Bash
cat > broken.R <<'R'
Print("Hello, World!")
R
Bash
Rscript broken.R

R stops with could not find function "Print". The same error appears when you call a function from a package you have not loaded with library.

Counting from zero. Coming from another language, you might write spend[0] for the first item. R does not stop with an error; it returns an empty vector, numeric(0), which can quietly break later steps. The first item is spend[1].

Spaces around the arrow. x<-5 stores 5 in x, but x < -5 asks whether x is less than minus five. Always write x <- 5 with a space on each side.

Curly quotes. Code copied from a word processor or a chat app may contain curly quotes (“ ”) instead of straight ones (" "). R reports unexpected input and points at the quote. Retype the quotes in a plain text editor.

When you have finished, remove the practice folder:

Bash
cd ~
rm -rf ~/hello-r-demo

Check it worked

Running hello.R from the wrong folder fails with cannot open file, broken.R fails with could not find function "Print", and after the last command ls ~/hello-r-demo reports that the folder no longer exists.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.