R Programming – Week 2 Learning Material

Comprehensive Study Notes

1. Data Types

TypeDescriptionExamples
NumericNumbers with/without decimals and numeric NA.23, 0.03, NA
CharacterText enclosed in quotes.'hello', "R"
LogicalTRUE or FALSE.TRUE, FALSE
VectorCollection of same data type.c(1,2,3)
NAMissing value.NA
class(2)
class('hello')
class('23')
class(FALSE)
class(NA)

print('Boina Avinash Kumar')

2. Variables

Variables store information using the assignment operator <- (preferred) or =.

full_name <- "Natalia Rodríguez Nuñez"
message_string <- "Hello there"
print(message_string)

message_string <- "Hasta la vista"
print(message_string)

3. Vectors

Vectors are list-like structures containing values of the same type.

spring_months <- c("March","April","May","June")

typeof(spring_months)
length(spring_months)
spring_months[2]
Task: Create a numeric vector named phone containing area code, next three digits and last four digits.

4. Conditional Statements

if(TRUE){
 print("This message will print!")
}

if(TRUE){
 print("Go to sleep!")
}else{
 print("Wake up!")
}

message <- "I change based on a condition."
if(TRUE){
 message="I execute this when true!"
}else{
 message="I execute this when false!"
}
print(message)

5. Comparison Operators

10 < 12
56 >= 129
56 != 129

6. Logical Operators

if(stopLight=='green' & pedestrians==0){
 print('Go!')
}else{
 print('Stop')
}

if(day=='Saturday' | day=='Sunday'){
 print('Enjoy the weekend!')
}

excited <- TRUE
print(!excited)

7. Functions

Functions perform reusable tasks.

sort(c(2,4,10,5,1))
length(c(2,4,10,5,1))
sum(5,15,10)

data <- c(120,22,22,31,15,120)
unique_vals <- unique(data)
print(unique_vals)

solution <- sqrt(49)

round_down <- floor(3.14)
round_up <- ceiling(3.14)

Important Functions: sort(), length(), sum(), unique(), sqrt(), floor(), ceiling()

8. Importing Packages

install.packages('dplyr')
library(dplyr)
library(readr)

artists <- read_csv('artists.csv')

artists %>%
 select(-country,-year_founded,-albums) %>%
 filter(spotify_monthly_listeners > 20000000,
        genre != "Hip Hop") %>%
 arrange(desc(youtube_subscribers))

Pipeline (%>%)

The pipe operator passes the output of one function directly as input to the next.

dplyr Steps

  1. select() – removes unwanted columns.
  2. filter() – filters rows based on conditions.
  3. arrange(desc()) – sorts rows in descending order.

9. RStudio Tips

10. Summary