R Tutorial menu

R Lists, Matrices and Factors

Lists, matrices and factors let you store data that does not fit in a simple vector.

Which One to Use?

StructureHoldsExample
VectorValues of one type, in a lineFive students' marks
ListValues of any types, even other vectorsOne student's name, age and marks
MatrixValues of one type, in rows and columnsMonthly sales of two shops
FactorCategories with a fixed set of levelsShirt sizes S, M, L

Lists

A list can hold different types together. Give each part a name:

Example

r
student <- list(name = "Ali", age = 19, marks = c(80, 72, 91))
student
Output
$name
[1] "Ali"

$age
[1] 19

$marks
[1] 80 72 91

Getting Items from a List

Use $ with the name, or double brackets [[ ]]:

Example

r
student$name
student[["marks"]]
mean(student$marks)
Output
[1] "Ali"
[1] 80 72 91
[1] 81

Single brackets student["marks"] return a smaller list, not the values themselves. Use $ or [[ ]] when you want the actual values to calculate with.

Adding and Removing Items

Assign a new name to add an item. Assign NULL to remove one:

Example

r
student$city <- "Karachi"
student$age <- NULL
names(student)
length(student)
Output
[1] "name"  "marks" "city" 
[1] 3

Many R functions return their results as lists, so you will meet lists often, even if you rarely create them yourself.

Matrices

A matrix is a table of values of one type, with rows and columns. Create it with matrix():

Example

r
m <- matrix(1:6, nrow = 2)
m
dim(m)
Output
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[1] 2 3

By default, R fills the matrix column by column. Add byrow = TRUE to fill it row by row. dim() gives the number of rows and columns.

A Matrix with Names

Here are the sales (in thousands of rupees) of two shops over three months:

Example

r
sales <- matrix(c(120, 95, 140, 110, 80, 130), nrow = 2, byrow = TRUE,
                dimnames = list(c("Shop A", "Shop B"), c("Jan", "Feb", "Mar")))
sales
sales["Shop B", "Feb"]
sales[1, ]
Output
       Jan Feb Mar
Shop A 120  95 140
Shop B 110  80 130
[1] 80
Jan Feb Mar 
120  95 140 

Inside the brackets, the first number is the row and the second is the column: [row, column]. Leave one empty to get the whole row or column.

Row and Column Totals

Example

r
rowSums(sales)
colMeans(sales)
Output
Shop A Shop B 
   355    320 
  Jan   Feb   Mar 
115.0  87.5 135.0 
FunctionGives
rowSums(), colSums()Totals of each row or column
rowMeans(), colMeans()Averages of each row or column
t()Swaps rows and columns
nrow(), ncol()Number of rows or columns

Factors

A factor stores categories. R keeps a list of the possible values, called levels:

Example

r
sizes <- c("M", "L", "S", "M", "M", "L")
size_factor <- factor(sizes)
size_factor
levels(size_factor)
table(size_factor)
Output
[1] M L S M M L
Levels: L M S
[1] "L" "M" "S"
size_factor
L M S 
2 3 1 

table() counts how many times each level appears. A Karachi clothes shop could use this to see which size sells most.

Choosing the Order of Levels

R sorts levels alphabetically, so L came before S. Give the order yourself with levels =:

Example

r
size_factor <- factor(sizes, levels = c("S", "M", "L"))
table(size_factor)
nlevels(size_factor)
Output
size_factor
S M L 
1 3 2 
[1] 3

Factors are important for statistics and charts. They tell R that a column holds groups, not free text.

Exercise

Exercise

You need to store one student's name (text), age (number) and five marks together. Which structure fits best?

Learn R with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp