1. Data Types
| Type | Description | Examples |
|---|---|---|
| Numeric | Numbers with/without decimals and numeric NA. | 23, 0.03, NA |
| Character | Text enclosed in quotes. | 'hello', "R" |
| Logical | TRUE or FALSE. | TRUE, FALSE |
| Vector | Collection of same data type. | c(1,2,3) |
| NA | Missing 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
- < Less Than
- > Greater Than
- <= Less Than or Equal
- >= Greater Than or Equal
- == Equal
- != Not Equal
10 < 12
56 >= 129
56 != 129
6. Logical Operators
- & AND
- | OR
- ! NOT
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
- select() – removes unwanted columns.
- filter() – filters rows based on conditions.
- arrange(desc()) – sorts rows in descending order.
9. RStudio Tips
- Customize RStudio layout from Preferences.
- Ctrl + Enter executes current line.
- Create plots using
plot(x,y,type='b'). - Export plots as Image or PDF.
- Help commands:
?install.packagesand??install.
10. Summary
- Understand R data types and variables.
- Create and manipulate vectors.
- Use conditional statements and logical operators.
- Apply comparison operators.
- Call built-in functions effectively.
- Install and import packages.
- Use dplyr for data manipulation.
- Use RStudio shortcuts and documentation.