R is a free programming language built specifically for statistics, data analysis, and graphics. This page gets you from zero to writing and understanding your first R code.
What Is R?
R is an open-source language used by statisticians, data scientists, and researchers to analyse data, run statistical tests, and create charts. Unlike general-purpose languages, R was built from the ground up around one idea: working with data should be simple and natural.
You can install R for free from cran.r-project.org, and most people also install RStudio — a free, friendly editor that makes writing and running R code much easier (console, script editor, plot viewer, and file browser all in one window).
Your First Line of R Code
Open R or RStudio and type the following into the console, then press Enter.
print("Hello, World!")
[1] "Hello, World!"
The [1] in front of the output just means "this is the first element of the result" — you will see this a lot in R, because almost everything in R is technically a vector (a sequence of values), even a single line of text.
Variables and Assignment
A variable stores a value so you can reuse it later. In R, the idiomatic way to assign a value to a variable is the arrow <- (you can also use =, but <- is what most R code and documentation use).
name <- "Rafi" age <- 23 is_student <- TRUE print(name) print(age) print(is_student)
[1] "Rafi" [1] 23 [1] TRUE
print() — typing name alone in the console shows the same output. Using print() is only required inside loops, functions, or scripts that don't auto-print results.Basic Data Types
Every value in R belongs to one of a handful of basic types. Knowing these is the foundation for everything else in this guide.
- numeric — any number with or without decimals, e.g.
10,3.14 - integer — whole numbers, written with an
Lsuffix, e.g.5L - character — text, always in quotes, e.g.
"hello" - logical —
TRUEorFALSE - complex — numbers with an imaginary part, e.g.
2+3i(rarely used by beginners)
Use class() to check the type of any value or variable:
class(10) class(5L) class("hello") class(TRUE)
[1] "numeric" [1] "integer" [1] "character" [1] "logical"
Comments
Anything after a # on a line is a comment — R ignores it completely. Comments explain your code to your future self (and to anyone else reading it).
# this calculates the area of a circle radius <- 5 area <- pi * radius^2 # pi is a built-in constant area
[1] 78.53982
Getting Help
R has excellent built-in documentation. If you ever forget how a function works, don't guess — ask R directly.
?mean # opens the help page for mean() help("sum") # same thing, alternate syntax args(round) # shows just the arguments a function accepts
Key Points
- R is free, open-source, and purpose-built for statistics and data analysis.
- Use
<-to assign values to variables. - Every value has a type: numeric, integer, character, logical, or complex.
- Use
class()to check a value's type, and?function_nameto get help.