Skip to content
AgileLogics
4 min read

Your First R Program

Prerequisites: Installing R and RStudio

Type this into the console and press Enter:

print("Hello, world!")

Expected output

[1] "Hello, world!"
  • print(...) displays a value.
  • "Hello, world!" is a string — text in quotes.
  • The [1] at the start isn't part of your data. R numbers the elements of its output, and [1] means "this line starts with element number 1". You'll see why that's useful in the Vectors lesson.

The console prints automatically

In the console (and in scripts run with source and echo), typing a value on its own prints it:

2 + 3
"Learning R"
[1] 5
[1] "Learning R"

cat: print without the [1]

cat() prints text plainly, without quotes or numbering. Add "\n" for a new line:

cat("Hello, world!\n")
cat("2 + 3 =", 2 + 3, "\n")
Hello, world!
2 + 3 = 5

cat separates its arguments with spaces.

Running a script

Save code in a file such as hello.R and run it with Source in RStudio, or from a terminal:

Rscript hello.R

Common mistakes

  • Mismatched quotes or parentheses. The console then shows a + prompt, meaning "I'm waiting for you to finish the line". Press Esc to cancel and try again.
  • R is case-sensitive: Print("hi") fails with could not find function "Print".

Practice

Use cat to print your name on one line and your favorite food on the next.

Show solution
cat("Ada\n")
cat("Pizza\n")
Ada
Pizza