R First Program

Writing your first R program is the best way to move from reading about R to actually using it. This topic walks through several small programs that teach you core R concepts while producing visible results right away.

The Classic Hello World Program

Every programming course starts with a program that displays the words "Hello, World!" on the screen. In R, you do this with the print() function.

print("Hello, World!")

Output:

[1] "Hello, World!"

The [1] at the start of the output is R's way of saying "this is the first element of the result." You will see this in almost every output R produces. It is normal and not an error.

How a Simple Program Flows

You write:   print("Hello, World!")
                        │
                        ▼
          R reads the instruction
                        │
                        ▼
          R finds the print() function
                        │
                        ▼
          R displays:  [1] "Hello, World!"

Basic Arithmetic in R

R works like a calculator. You type a math expression and R gives the answer.

# Addition
10 + 5

# Subtraction
20 - 8

# Multiplication
6 * 7

# Division
100 / 4

# Power
2 ^ 10

Output:

[1] 15
[1] 12
[1] 42
[1] 25
[1] 1024

R evaluates each expression and shows the result immediately in the console.

Storing a Value in a Variable

Instead of just calculating things, you can store results for later use. R uses the <- symbol (called the assignment operator) to store values.

age <- 30
print(age)

Output:

[1] 30

The name age now holds the value 30. You can use it in calculations:

age <- 30
years_to_retire <- 60 - age
print(years_to_retire)

Output:

[1] 30

A Program That Greets a Person

This small program combines text and a variable to create a custom greeting.

name <- "Priya"
greeting <- paste("Hello,", name, "! Welcome to R.")
print(greeting)

Output:

[1] "Hello, Priya ! Welcome to R."

The paste() function joins pieces of text together. You will use it frequently when working with text in R.

Diagram: How R Processes Your Program

  Script File (.R)
  ┌────────────────────────┐
  │ name <- "Priya"        │
  │ greeting <- paste(...) │
  │ print(greeting)        │
  └────────┬───────────────┘
           │
           ▼
    R Engine reads top to bottom
           │
           ▼
   ┌────────────────────┐
   │  Memory (RAM)      │
   │  name = "Priya"    │
   │  greeting = "..."  │
   └────────┬───────────┘
            │
            ▼
      Console Output
      [1] "Hello, Priya ! Welcome to R."

A Program That Does Calculations on Data

Here is a slightly more useful program — it calculates the average of five test scores.

scores <- c(85, 92, 78, 95, 88)
average <- mean(scores)
print(average)

Output:

[1] 87.6

The c() function creates a list of values called a vector. The mean() function calculates the average of all values in that vector. You did not need to add them and divide manually — R handled it in one step.

Using cat() to Display Output

The cat() function is another way to print output. It gives you more control over formatting.

name <- "Ravi"
score <- 95
cat("Student:", name, "\nScore:", score, "\n")

Output:

Student: Ravi
Score: 95

The \n inside the text means "new line." The difference between print() and cat() is that print() adds quotes and the [1] prefix, while cat() shows plain text output.

Good Habits From Your First Program

  • Always save your script with a .R extension before running it
  • Use meaningful variable names like total_price instead of tp
  • Run one section at a time while learning — do not run everything at once
  • Read the error message when something goes wrong — R usually tells you exactly what the problem is

What Happens When There Is an Error

print(hello)

Output:

Error in print(hello) : object 'hello' not found

R gives a clear error because hello was never defined as a variable. The fix is to either define it first (hello <- "Hi") or put quotes around it (print("hello")). Errors are a normal part of learning — every programmer encounters them daily.

Your first programs do not need to be complicated. Every expert R programmer started by running simple lines like the ones on this page. Build the habit of typing and running code yourself rather than just reading examples.

Leave a Comment

Your email address will not be published. Required fields are marked *