Looks like no one added any tags here yet for you.
Variables can be created using <-
or =
.
name <- "Girlypop" # String
age <- 16 # Numeric
is_student <- TRUE # Boolean (TRUE/FALSE)
# Let's print these out!
print(name)
print(age)
print(is_student)
R has multiple data structures like vectors, data frames, and lists.
Vectors
Vectors are like arrays in other languages, holding elements of the same type.
# Vector of numbers
numbers <- c(1, 2, 3, 4, 5)
print(numbers)
# Vector of characters (strings)
fruits <- c("apple", "banana", "strawberry")
print(fruits)
Data frames are used to store tabular data. Think of them as little spreadsheets.
# Create a data frame
students <- data.frame(
Name = c("Maya", "Rosa", "Ava"),
Grade = c(90, 85, 95),
Passed = c(TRUE, TRUE, TRUE)
)
# View the data frame
print(students)
If-Else Statements
Control the flow of your program with conditions.
# If-else example
grade <- 95
if (grade >= 90) {
print("A+ girlypop!")
} else {
print("Keep working hard!")
}
For Loops Repeat actions a specific number of times.
# For loop to print numbers
for (i in 1:5) {
print(paste("This is loop number", i))
}
While Loops Repeat until a condition is false.
# While loop example
counter <- 1
while (counter <= 3) {
print(paste("Counter is", counter))
counter <- counter + 1
}
Functions in R allow you to write reusable code.
# Define a function
sparkle <- function(name, mood) {
paste(name, "is feeling", mood, "and ready to conquer the world!")
}
# Call the function
message <- sparkle("Girlypop", "fabulous")
print(message)
You can read in data from CSV files.
# Install ggplot2 if not already
install.packages("ggplot2")
library(ggplot2)
# Create a simple plot
ggplot(students, aes(x = Name, y = Grade)) +
geom_bar(stat = "identity", fill = "lightpink") +
ggtitle("Student Grades") +
theme_minimal()
If you’re into data science, R is great for machine learning! Here's a super quick intro.
# Install caret package for ML
install.packages("caret")
library(caret)
# Example: Splitting data into training and test sets
data(iris)
set.seed(123)
trainIndex <- createDataPartition(iris$Species, p = .8, list = FALSE)
trainSet <- iris[trainIndex, ]
testSet <- iris[-trainIndex, ]
# Train a decision tree model
install.packages("rpart")
library(rpart)
model <- rpart(Species ~ ., data = trainSet)
# Predict on the test set
predictions <- predict(model, testSet, type = "class")
print(predictions)