R Tutorial menu

R Data Frames

A data frame is a table with rows and columns, like a sheet in Excel, and it is how R stores most real data.

Creating a Data Frame

Each column is a vector, and all columns have the same length. Unlike a matrix, different columns can have different types:

Example

r
students <- data.frame(
  name  = c("Ali", "Ayesha", "Bilal", "Sana", "Hamza"),
  city  = c("Karachi", "Lahore", "Karachi", "Multan", "Karachi"),
  marks = c(78, 92, 65, 88, 71)
)
students
Output
    name    city marks
1    Ali Karachi    78
2 Ayesha  Lahore    92
3  Bilal Karachi    65
4   Sana  Multan    88
5  Hamza Karachi    71

The numbers on the left are row numbers.

Looking at a Data Frame

Example

r
nrow(students)
names(students)
str(students)
Output
[1] 5
[1] "name"  "city"  "marks"
'data.frame':	5 obs. of  3 variables:
 $ name : chr  "Ali" "Ayesha" "Bilal" "Sana" ...
 $ city : chr  "Karachi" "Lahore" "Karachi" "Multan" ...
 $ marks: num  78 92 65 88 71
FunctionWhat it shows
head(df), tail(df)The first or last 6 rows
nrow(), ncol(), dim()Number of rows and columns
names()Column names
str()Each column's type and first values
summary()Quick statistics for each column

In RStudio, View(students) opens the data frame in a spreadsheet-like window. It is the easiest way to look at a big table.

Selecting Columns and Rows

Use $ for one column. Use [row, column] like a matrix:

Example

r
students$marks
mean(students$marks)
students[2, ]
Output
[1] 78 92 65 88 71
[1] 78.8
    name   city marks
2 Ayesha Lahore    92

Filtering Rows

Put a condition in the row position to keep only matching rows:

Example

r
students[students$marks > 75, ]
students[students$city == "Karachi", c("name", "marks")]
Output
    name    city marks
1    Ali Karachi    78
2 Ayesha  Lahore    92
4   Sana  Multan    88
   name marks
1   Ali    78
3 Bilal    65
5 Hamza    71

subset() does the same with shorter code, because you do not need to repeat students$:

Example

r
subset(students, marks >= 70 & city == "Karachi")
Output
   name    city marks
1   Ali Karachi    78
5 Hamza Karachi    71

Adding a Column

Assign to a new column name. ifelse() picks one of two values for every row:

Example

r
students$result <- ifelse(students$marks >= 70, "Pass", "Fail")
students
Output
    name    city marks result
1    Ali Karachi    78   Pass
2 Ayesha  Lahore    92   Pass
3  Bilal Karachi    65   Fail
4   Sana  Multan    88   Pass
5  Hamza Karachi    71   Pass

Sorting Rows

order() gives the row positions in sorted order:

Example

r
students[order(students$marks, decreasing = TRUE), ]
Output
    name    city marks result
2 Ayesha  Lahore    92   Pass
4   Sana  Multan    88   Pass
1    Ali Karachi    78   Pass
5  Hamza Karachi    71   Pass
3  Bilal Karachi    65   Fail

Adding a Row

rbind() joins rows. The new row must have the same column names:

Example

r
new_row <- data.frame(name = "Zara", city = "Quetta", marks = 84, result = "Pass")
students <- rbind(students, new_row)
nrow(students)
Output
[1] 6

Summarising Data

Example

r
table(students$city)
aggregate(marks ~ city, data = students, FUN = mean)
Output

Karachi  Lahore  Multan  Quetta 
      3       1       1       1 
     city    marks
1 Karachi 71.33333
2  Lahore 92.00000
3  Multan 88.00000
4  Quetta 84.00000

aggregate(marks ~ city, ...) means "average the marks for each city". The ~ sign is read as "by".

Reading and Writing CSV Files

Real data usually comes from a file. Save a sheet from Excel as CSV, then:

Example

r
shop <- read.csv("sales.csv")
head(shop)
write.csv(students, "students.csv", row.names = FALSE)

read.csv() looks for the file in your working directory. Use getwd() to see which folder that is, or choose it in RStudio from Session, Set Working Directory.

For larger projects, many R users load the dplyr package. It gives easy-to-read functions like filter(), arrange() and summarise() for the same jobs you learned here.

Exercise

Exercise

Which code keeps only the rows of the students data frame where marks are above 80?

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