R-volution

1. Setting Up R

First, make sure you have R and RStudio installed on your computer. RStudio provides a user-friendly interface for R.

2. Basic R Syntax

You can start R and type commands in the console. Here are some basic operations:

# Assigning variables
x <- 10
y <- 5

# Basic arithmetic
sum <- x + y
product <- x * y

# Print results
print(sum)
print(product)

3. Working with Vectors

Vectors are one of the most basic data structures in R.

# Creating a vector
my_vector <- c(1, 2, 3, 4, 5)

# Accessing elements
first_element <- my_vector[1]  # Access the first element
print(first_element)

# Vector operations
squared_vector <- my_vector^2
print(squared_vector)

4. Data Frames

Data frames are used to store tabular data.

# Creating a data frame
my_data <- data.frame(
  Name = c("Alice", "Bob", "Charlie"),
  Age = c(25, 30, 35),
  Height = c(5.5, 6.0, 5.8)
)

# Viewing the data frame
print(my_data)

# Accessing columns
ages <- my_data$Age
print(ages)

5. Data Manipulation with dplyr

dplyr is a powerful package for data manipulation.

# Install dplyr if you haven't already
install.packages("dplyr")
library(dplyr)

# Filtering data
filtered_data <- my_data %>% filter(Age > 28)
print(filtered_data)

# Summarizing data
summary_data <- my_data %>% summarize(Average_Age = mean(Age))
print(summary_data)

6. Data Visualization with ggplot2

ggplot2 is a popular package for creating visualizations.

# Install ggplot2 if you haven't already
install.packages("ggplot2")
library(ggplot2)

# Creating a scatter plot
ggplot(my_data, aes(x = Age, y = Height)) +
  geom_point() +
  ggtitle("Age vs Height") +
  xlab("Age") +
  ylab("Height")

7. Basic Statistical Analysis

You can perform statistical analyses such as t-tests or linear regression.

# Performing a t-test
t_test_result <- t.test(my_data$Height ~ my_data$Age > 28)
print(t_test_result)

# Linear regression
model <- lm(Height ~ Age, data = my_data)
summary(model)

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *