R Beginners Course 2026

Dr. Debasish Mukherjee, Dr. Ulrike Göbel, Dr. Ali Abdallah

Bioinformatics Core Facility CECAD

2026-05-11

Session 2 :: Basic Concepts in R

Variables

  • Variables are containers for storing data values.
  • R does not have a command for declaring a variable
  • A variable is created the moment you first assign a value to it.
  • Assignment operator <- or = can be used for assigning a value

Code
# This is a comment

name <- "John"    # This is also a comment
age <- 40
name
[1] "John"
Code
name <- "Tom"
print (name)
[1] "Tom"

Variable Names

Variable names may be short (like x and y) or descriptive (age, carname, total_volume).

 

Rules for R variable names are:

  • A variable name must start with a letter or a period.
  • It can be a combination of letters, digits, period(.) and underscore(_).
  • If it starts with a period, then the period must not be followed by a digit.
  • It is case sensitive.

Variable Names

Allowed variable names:

myvar    <- "John"
my_var   <- "John"
myvar_2. <- "John"
.myvar   <- "John"

# These assignments do not overwrite "myvar":
myVar    <- "Jenny"
MYVAR    <- "Cathy"

Forbidden variable names:

my var  <- "John"  # space
           
2myvar  <- "John"  # starts with a number
.2myvar <- "John"  # starts with a '.' plus number
my-var  <- "John"  # special character
_my_var <- "John"  # starts with a '_'
my_var% <- "John"  # special character
TRUE    <- "John"  # reserved words

Basic Data Types

Each R object has a data type (for object x, query it with class(x)). Variables have the type of the assigned object.

Data Type (Class) Example Verify value
Character “Hello!” x<-"Hello!" print(x) class(x)
Hello!
character
Numeric (double) 1.3, 5, 4.2

x<-1.35

print(x) class(x)


1.35
numeric

Numeric (integer) 1L, 0L, 4L

x<-35L

print(x) class(x)


35
integer

Complex 2+3i x<-2+3i print(x) class(x)
2+3i
complex
Logical TRUE / FALSE x<-TRUE print(x) class(x)
TRUE
logical

R Data Structures

More complex data structures (often also called data types) are composed from the basic data types. The frequently used ones are −

A vector is a “chain” of one or more instances of one data type:

numbers <- c(100, 200, 450, 670) # create a vector

 # set element names (the names are also a vector!)
names(numbers) <- c("a",'b','c',"d")

print(numbers) # print the whole vector
  a   b   c   d 
100 200 450 670 
numbers[1]   # print first element by index
  a 
100 
numbers["a"] # print first element by name 
  a 
100 
is.vector(numbers)
[1] TRUE
is.vector(numbers[1])
[1] TRUE

Most mathematical R operators and many R functions are vectorizing, that is,
they can operate on vectors of any length:

v1 <- 1:3 # define the numeric vector c(1,2,3) 
          # by start and end
v1
[1] 1 2 3
v2 <- c(1,7,14)
v2
[1]  1  7 14

 

v1 + v2
[1]  2  9 17

What happens if we combine vectors of unequal length ?

# a vector of type "character"
v1 <- c("A","B","C","D","E")  
v1
[1] "A" "B" "C" "D" "E"
v2 <- c("X","Y")
v2
[1] "X" "Y"

 

# use the paste() function to glue pairs of elements 
# of v1 and v2 together: 
paste(v1,v2,sep="|")
[1] "A|X" "B|Y" "C|X" "D|Y" "E|X"

Recycling combines a length-1 vector with every element of a longer vector.  
This is useful for vector-by-number arithmetic operations:

v <- c(1,4,0,2,-4)
v * 2
[1]  2  8  0  4 -8

# Create a matrix.
M = matrix( c(2,10,-4,0,7,5.5), 
            nrow = 2, 
            ncol = 3, 
            byrow = TRUE,
            dimnames = 
              list(Sex=c("F","M"),Day=1:3))

# Print the matrix
print(M)
   Day
Sex 1  2    3
  F 2 10 -4.0
  M 0  7  5.5

 

nrow(M) # Get the number of rows
[1] 2
M[1,] # Extract the first row
 1  2  3 
 2 10 -4 
ncol(M) # Get the number of columns
[1] 3
M[,1] # Extract the first column
F M 
2 0 

# Create an array with 3 dimensions:
a <- array(dim = c(2,3,2))

# Assume that Dimension 3 (=z) relates to 
# two experiments in different conditions,
a[,,1] <- M     # condition 1 
a[,,2] <- M + 2 # condition 2 

# Print the array
print(a)
, , 1

     [,1] [,2] [,3]
[1,]    2   10 -4.0
[2,]    0    7  5.5

, , 2

     [,1] [,2] [,3]
[1,]    4   12 -2.0
[2,]    2    9  7.5

Lists are vectors of a special kind.  
A list element is not in itself a data value, but a "hook" which may attach an arbitrary R object.

L <- list(c(), c(), c())
length(L)
[1] 3
# L itself has data type "list"
class(L) 
[1] "list"
# and each of its elements, too
# (as a vector should!)
class(L[1]) 
[1] "list"

Each hook can attach an R object:  

L <- list(date = date(), 
          mouse = c("M5|1"), 
          treatment = 
            list( 
              doses = c(drug1=5,
                        drug2=15),
              technician = "Amy"
            )
     )

A list can mirror the structure of a dataset in an R object.  
Individual components can be extracted by index or by name:

#  Double brackets extract the value of an element
L[[2]] 
[1] "M5|1"
# Two more ways to retrieve the value:
L[["mouse"]]
[1] "M5|1"
L$mouse
[1] "M5|1"
# Single brackets extract the entire 2nd list element:
L[2]
$mouse
[1] "M5|1"
# Extract a component of a sub-list:
L$treatment$doses
drug1 drug2 
    5    15 
# Create the data frame
BMI <-  data.frame(
   gender = c("Male", "Male","Female"), 
   height = c(152, 171.5, 165), 
   weight = c(81,93, 78),
   Age = c(42,38,26)
)

# Print the data frame
print(BMI)
  gender height weight Age
1   Male  152.0     81  42
2   Male  171.5     93  38
3 Female  165.0     78  26

 

# Print column "Age"
print(BMI[,"Age"]) # alternatively: print(BMI$Age)
[1] 42 38 26
# Print second row:
print(BMI[2,])
  gender height weight Age
2   Male  171.5     93  38

The factor data type describes relationships between categories. A factor variable is typically used to group another variable according to these categories, and then run statistical tests of category differences on this variable.  

Often, the grouping variable and the grouped variable are columns in the same dataframe.

An unordered factor distinguishes a single base category (= the base level = level 1)
Other categories are tested against this base level.

apple_colors <- 
  c('green','green','yellow','red','red','red','green')

df <-
  data.frame(
    sugar = c(0.5, 0.1, 1.4, 2.3, 1.9, 3.0, 0.9),
    color = factor(apple_colors, 
                   ordered = FALSE, # default 
                   
                   # IF NOT SET, ORDER IS ALPHABETIC!
                   levels = c("green","yellow","red"))
  )
print(df)
  sugar  color
1   0.5  green
2   0.1  green
3   1.4 yellow
4   2.3    red
5   1.9    red
6   3.0    red
7   0.9  green
print(df$color)
[1] green  green  yellow red    red    red    green 
Levels: green yellow red

An ordered factor defines an order on all levels. This allows to test whether the trend of some variable (here: sugar content) follows this order.

df <-
  data.frame(
    sugar = c(0.5, 0.1, 1.4, 2.3, 1.9, 3.0, 0.9),
    
    # Need to set ordered=TRUE to get an ordered factor!
    color = factor(apple_colors, 
                   ordered =TRUE,
                   levels = c("green","yellow","red"))
  )
print(df)
  sugar  color
1   0.5  green
2   0.1  green
3   1.4 yellow
4   2.3    red
5   1.9    red
6   3.0    red
7   0.9  green
print(df$color)
[1] green  green  yellow red    red    red    green 
Levels: green < yellow < red

Operators

Operators are the symbols that tell the compiler to perform specific mathematical or logical manipulations. R language is rich in built-in operators and provides the following types of operators −

Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
^ Exponent x ^ y
%% Modulus (Remainder from division) x %% y
%/% Integer Division x%/%y
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal to x >= y
<= Less than or equal to x <= y
Operator Description
&& Statement-wise Logical AND operator: Returns TRUE if left and right statement is TRUE
& Vectorizing Logical AND operator
|| Statement-wise Logical OR operator: Returns TRUE if one of the statements is TRUE.
| Vectorizing Logical OR operator.
! Logical NOT - returns FALSE if statement is TRUE
my_var <- 3

3 -> my_var

assign("my_var", c(10.4, 5.6, 3.1, 6.4, 21.7))

my_var # print my_var
[1] 10.4  5.6  3.1  6.4 21.7
Operator Description Example
: Creates a series of numbers in a sequence x <- 1:10
%in% Find out if an element belongs to a vector x %in% y
%*% Matrix Multiplication x <- Matrix1 %*% Matrix2