filter rows meeting a condition
R is a powerful programming language widely used for statistical computing, data analysis, and creating high-quality visualizations. As a open source language, R benefits from an active community of developers contributing packages for various applications. While R has a steeper learning curve than Python, it provides a comprehensive environment for data science and remains popular among statisticians and researchers.
In this guide, we‘ll cover the fundamentals of programming in R, from basic variables and data structures to more advanced topics like data manipulation with dplyr and creating visualizations using ggplot2. Whether you‘re an aspiring data scientist or analyst, learning R is a valuable skill to add to your toolkit. Let‘s get started!
Variables and Assignment
At its core, programming involves storing and manipulating data using variables. In R, we use the assignment operator <- to assign values to variables:
x <- 42 # assign value 42 to variable x
y <- "hello" # assign text string to variable y
z <- TRUE # assign logical/boolean value to z
R is a dynamically-typed language, meaning you don‘t have to explicitly define a variable‘s data type; R will infer it based on the value assigned. The <- arrow-like operator is the preferred assignment operator, but R also supports using = for assignment. However, I recommend sticking with <- for clarity.
To print out a variable‘s value, simply type its name on a new line:
x # prints 42
y # prints "hello"
Data Structures
R provides several fundamental data structures for organizing and storing data. Here are the key ones to know:
Vectors
The most basic data structure in R is a vector, which is a sequence of elements of the same data type (numeric, character, logical). Create vectors using the c() function:
num_vec <- c(1, 2, 3, 4, 5)
char_vec <- c("a", "b", "c")
logical_vec <- c(TRUE, FALSE, TRUE, FALSE)
Matrices and Arrays
For multi-dimensional data, use matrices and arrays. A matrix is a 2D structure where all elements have the same data type. Create matrices with the matrix() function, specifying the data, number of rows, and number of columns:
my_matrix <- matrix(1:6, nrow=2, ncol=3)
Arrays extend matrices to n dimensions and are created using the array() function.
Lists
Lists are flexible structures that can contain elements of different data types, including other lists. Create lists using list():
my_list <- list(1, "apple", TRUE, c(2,3,4))
Accessing list elements requires double brackets [[]].
Factors
Factors are used for categorical data and can be ordered or unordered. They are created with the factor() function.
Data Frames
Rectangular data (like you‘d see in a spreadsheet) is stored in R as a data frame. Each column must have the same number of elements but can be a different data type. Create data frames using data.frame():
df <- data.frame(x = 1:3, y = c("a","b","c"), z = c(TRUE,FALSE,TRUE))
Data frames are two-dimensional, so you can think of them as a list of vectors, where each vector is a column.
Accessing Elements
Square brackets [] are used to access elements of vectors, matrices, and data frames:
my_vec <- c(10, 20, 30, 40, 50)
my_vec[1] # first element
my_vec[2:4] # second to fourth elements
my_vec[c(1,3,5)] # first, third, fifth elements
my_df <- data.frame(x=1:3, y=c(10,20,30))
my_df[1,2] # element in 1st row, 2nd column
my_df[,2] # all of 2nd column
The $ operator is used to access a specific column of a data frame by name: my_df$x.
Importing Data
Before analyzing data, you‘ll need to load it into R. The built-in read.table() and read.csv() functions can read in tabular data:
my_data <- read.csv("data.csv")
my_data <- read.table("data.txt", sep="\t", header=TRUE)
There are also packages like readxl and jsonlite for importing from Excel files and JSON. Once loaded, you can examine your data using functions like head(), str(), and summary().
Control Flow
To control execution flow based on logical conditions, use if, else if, and else:
x <- 10
if (x > 0) {
print("Positive")
} else if (x < 0) {
print("Negative")
} else {
print("Zero")
}
Looping allows you to iterate over elements and avoid repetitive code:
for (i in 1:5) {
print(i)
}
my_vec <- c(1,1,2,3,5,8,13)
for (elem in my_vec) {
print(elem^2)
}
count <- 1
while (count <= 10) {
print(count)
count <- count + 1
}
Functions
Functions let you encapsulate reusable code and are defined using the function() keyword:
square <- function(x) {
return x^2
}
square(5) # prints 25
R has many useful built-in functions, and you can define your own for common operations you perform.
Data Manipulation with dplyr
The dplyr package provides an intuitive "grammar" for data manipulation, making it easy to transform and summarize data frames:
library(dplyr)
df <- data.frame(
name = c("John","Jane","Jim","Joan"),
age = c(23, 29, 43, 36),
income = c(48000, 71000, 64000, 59000)
)
filter(df, age > 30)
select(df, name, income)
mutate(df, income_thousands = income/1000)
df %>%
group_by(age > 30) %>%
summarize(mean_income = mean(income))
Using dplyr can greatly simplify the process of subsetting, aggregating, and joining datasets compared to base R syntax. Its chained operations using the pipe operator %>% promote readable, expressive code.
Visualization
Exploratory data analysis and communicating insights is made possible through R‘s extensive plotting capabilities. While base R provides fundamental plotting functions, the ggplot2 package implements a "grammar of graphics" for building precise, customized visualizations in layers.
Here‘s a simple scatterplot in base R:
plot(x = iris$Sepal.Length, y = iris$Sepal.Width,
col = iris$Species,
xlab = "Sepal Length", ylab = "Sepal Width",
main = "Sepal Length vs. Width")
legend("topright", legend = levels(iris$Species),
col = 1:3, pch = 16)
And the equivalent in ggplot2:
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width,
color = Species)) +
geom_point() +
labs(x = "Sepal Length", y = "Sepal Width",
title = "Sepal Length vs. Width")
ggplot2 offers many geoms like geom_point(), geom_bar(), geom_boxplot(), geom_histogram() for building common chart types and extensive options for customizing aesthetics. While it requires a bit more code, ggplot2 gives you greater control and reusable components.
Additional visualization packages to explore include plotly for interactive plots, leaflet for maps, and the grammar-of-graphics-inspired esquisse for drag-and-drop plot building.
What‘s Next?
We‘ve only scratched the surface of R‘s capabilities! As you progress, some next steps to consider:
- Explore the tidyr package for shaping data and the purrr package for functional programming.
- Dive into statistics and machine learning with packages like caret and the tidymodels suite.
- Build interactive web apps and dashboards using the Shiny framework.
- Automate reporting and create reproducible documents with rmarkdown.
- Contribute your own packages to CRAN or share on GitHub.
The rich ecosystem of open source packages is constantly evolving, making R a powerful tool for data science. Its roots in statistics, paired with modern tooling from RStudio, ensure that R will remain an important language to learn for data analysis and visualization.