Data frame
A data frame is a very important data type in R and is widely used for statistical
analysis.
Data Frames are data displayed in a format as a table.
Data Frames can have different types of data inside it. While the first column can
be character, the second and third can be numeric or logical.
However, each column should have the same type of data.
Use the [Link]() function to create a data frame:
# Create a data frame
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Print the data frame
Data_Frame
Summarize the Data
Use the summary() function to summarize the data from a Data Frame:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Data_Frame
summary(Data_Frame)
Access Items
We can use single brackets [ ], double brackets
[[ ]] or $ to access columns from a data frame:
Data_Frame <- [Link] (
Training =
c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
Data_Frame[1]
Data_Frame[["Training"]]
Data_Frame$Training
Add Rows
Use the rbind() function to add new rows in a Data Frame:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Add a new row
New_row_DF <- rbind(Data_Frame, c("Strength", 110, 110))
# Print the new row Training Pulse Duration
New_row_DF 1 Strength 100 60
2 Stamina 150 30
3 Other 120 45
4 Strength 110 110
Add Columns
Use the cbind() function to add new columns in a Data Frame:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Add a new column
New_col_DF <- cbind(Data_Frame, Steps = c(1000, 6000, 2000))
# Print the new column
New_col_DF
Training Pulse Duration Steps
1 Strength 100 60 1000
2 Stamina 150 30 6000
3 Other 120 45 2000
Remove Rows and Columns
Use the c() function to remove rows and columns in a Data Frame:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
# Remove the first row and column
Data_Frame_New <- Data_Frame[-c(1), -c(1)]
# Print the new data frame
Data_Frame_New Pulse Duration
2 150 30
3 3 120 45
=== Code Execution Successful ===
Amount of Rows and Columns
Use the dim() function to find the amount of rows and
columns in a Data Frame:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
dim(Data_Frame) [1] 3 3
You can also use the ncol() function to find the number of columns
and nrow() to find the number of rows:
Data_Frame <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
)
ncol(Data_Frame)
nrow(Data_Frame)
Combining Data Frames
Use the rbind() function to combine two or more data frames
in R vertically:
Data_Frame1 <- [Link] (
Training = c("Strength", "Stamina", "Other"), Training Pulse Duration
Pulse = c(100, 150, 120), 1 Strength 100 60
Duration = c(60, 30, 45) 2 Stamina 150 30
) 3 Other 120 45
4 Stamina 140 30
Data_Frame2 <- [Link] ( 5 Stamina 150 30
Training = c("Stamina", "Stamina", "Strength"), 6 Strength 160 20
Pulse = c(140, 150, 160),
Duration = c(30, 30, 20)
)
New_Data_Frame <- rbind(Data_Frame1, Data_Frame2)
New_Data_Frame
And use the cbind() function to combine two or more data frames
in R horizontally:
Data_Frame3 <- [Link] (
Training = c("Strength", "Stamina", "Other"),
Pulse = c(100, 150, 120),
Duration = c(60, 30, 45)
) Training Pulse Duration Steps Calories
1 Strength 100 60 3000 300
Data_Frame4 <- [Link] ( 2 Stamina 150 30 6000 400
Steps = c(3000, 6000, 2000), 3 Other 120 45 2000 300
Calories = c(300, 400, 300)
)
New_Data_Frame1 <- cbind(Data_Frame3, Data_Frame4)
New_Data_Frame1
Factors
Factors are used to categorize data.
Examples of factors are:
Demography: Male/Female
Music: Rock, Pop, Classic, Jazz
Training: Strength, Stamina
# Create a factor
music_genre <- factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
# Print the factor
music_genre
[1] Jazz Rock Classic Classic Pop Jazz Rock Jazz
Levels: Classic Jazz Pop Rock
You can see from the example above that that the factor has four levels
(categories): Classic, Jazz, Pop and Rock.
To only print the levels, use the levels() function:
Example
music_genre <- factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
levels(music_genre)
Factor Length
Use the length() function to find out how many items there are in the factor:
music_genre <-
factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
length(music_genre)
Access Factors
To access the items in a factor, refer to the index
number, using [] brackets:
music_genre <- factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
music_genre[3]
Change Item Value
To change the value of a specific item, refer to the index
number:
music_genre <-
factor(c("Jazz", "Rock", "Classic", "Classic", "Pop", "Jazz", "Rock", "Jazz"))
music_genre[3] <- "Pop"
music_genre[3]
In R, the arithmetic operators are:
Description Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division 5/2 2.5
^ or ** Exponentiation 2^3 8
Modulus
%% 5 %% 2 1
(remainder)
%/% Integer division 5 %/% 2 2
In R, the relational operators are used to compare values and return
a logical result (TRUE or FALSE).
Operator Description Example Result
== Equal to 5 == 3 FALSE
!= Not equal to 5 != 3 TRUE
> Greater than 5>3 TRUE
< Less than 5<3 FALSE
Greater than or
>= 5 >= 5 TRUE
equal to
Less than or equal
<= 3 <= 5 TRUE
to
The if Statement
An "if statement" is written with the if keyword, and it is used to specify a block of code
to be executed if a condition is TRUE:
a <- 33
b <- 200
if (b > a) {
print("b is greater than a")
}
Else If
The else if keyword is R's way of saying "if the previous conditions
were not true, then try this condition":
a <- 33
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print ("a and b are equal")
}
If Else
The else keyword catches anything which isn't caught by the preceding conditions:
a <- 200
b <- 33
if (b > a) {
print("b is greater than a")
} else if (a == b) {
print("a and b are equal")
} else {
print("a is greater than b")
}
R has two loop commands:
•while loops
•for loops
i <- 1
while (i < 6) {
print(i)
i <- i + 1
}
for (x in 1:10) {
print(x)
}
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
print(x)
}
dice <- c(1, 2, 3, 4, 5, 6)
for (x in dice) {
print(x)
}
fruits <- list("apple", "banana", "cherry")
for (x in fruits) {
if (x == "cherry") {
break
}
print(x)
}
1. Data Frame
Problem:
Create a data frame that stores the number of followers a person has on Twitter, Instagram,
and Facebook for 5 days.
Calculate the total followers gained on each day.
Find the day with the maximum followers gained.
# Create the dataframe
PostID <- c("P1", "P2", "P3", "P4", "P5")
Likes <- c(120, 340, 560, 230, 150)
Shares <- c(30, 50, 80, 40, 20)
social_data <- [Link](PostID, Likes, Shares)
# Print the dataframe
print("Social Media Data:")
print(social_data)
# Calculate totals
total_likes <- sum(social_data$Likes)
total_shares <- sum(social_data$Shares)
# Print totals
cat("Total Likes:", total_likes, "\n")
cat("Total Shares:", total_shares, "\n")
2. Matrix
Problem:
Create a matrix showing the number of likes and comments
for 3 posts on Instagram.
Rows represent posts, columns represent “Likes” and
“Comments”.
Calculate the total engagement (likes + comments) for each
post.
# Create a matrix for Likes and Comments
likes <- c(120, 250, 180) # Likes for 3 posts
comments <- c(15, 40, 25) # Comments for 3 posts
# Combine into a matrix (3 rows for posts, 2 columns for Likes & Comments)
engagement_matrix <- cbind(Likes = likes, Comments = comments)
# Print the matrix
print("Instagram Engagement Matrix:")
print(engagement_matrix)
# Calculate total engagement (Likes + Comments)
total_engagement <- rowSums(engagement_matrix)
# Add the total engagement as a new column
engagement_matrix <- cbind(engagement_matrix, Total = total_engagement)
# Print updated matrix
print("Matrix with Total Engagement:")
print(engagement_matrix)
Problem:
A company has monthly sales data for 6 months.
Write an R program to store the sales in a vector, then use a loop
to calculate:
The total sales.
The average monthly sales.
# Monthly sales data
sales <- c(12000, 15000, 18000, 17000, 16000, 20000)
# Initialize total
total_sales <- 0
# Loop to calculate total
for (month_sale in sales) {
total_sales <- total_sales + month_sale
}
# Calculate average
average_sales <- total_sales / length(sales)
# Display results
cat("Total Sales: ", total_sales, "\n")
cat("Average Monthly Sales: ", average_sales, "\n")