Use R base for stable, dependency-free data manipulation and statistical analysis. Many believe you need external packages for every task, but R base provides a complete environment for data cleaning, mathematical operations, and plotting without requiring additional installations.
R Base Data Structures and Object Creation
Understanding the core containers is the first step to using R base effectively. You will primarily work with vectors, lists, matrices, and data frames. A vector is the simplest object, containing elements of the same type. You create one using the c() function, which stands for combine. For example, c(1, 5, 10) creates a numeric vector. If you mix a number and a character string, R will convert everything to characters to maintain consistency.
Lists are more flexible than vectors because they can hold different types of objects, including other lists or data frames. You create these with the list() function. This is useful when you need to store a model result alongside the original data used to create it. Matrices are two-dimensional arrays where every element must be of the same type. You create them with matrix(data, nrow, ncol). If your data is shorter than the specified dimensions, R will recycle the values to fill the space.
The data frame is the most common structure for data analysis. It is essentially a list of vectors of equal length, where each vector represents a column. You create one using data.frame(). This structure allows you to store a mix of numeric, character, and logical data in a table format. To check the structure of any object you have created, use the str() function. This tells you the type of object and a preview of its contents, which prevents errors when you try to apply a function to the wrong data type.
Indexing and Subseting R Base Objects
Accessing specific pieces of data is done through square brackets []. For a simple vector, you place the index of the element you want inside the brackets. R uses 1-based indexing, meaning the first element is at position 1, not 0. To select multiple elements, pass a vector of indices, such as [c(1, 3, 5)].
Data frames require two indices: one for rows and one for columns, separated by a comma. The syntax is [row, column]. If you leave the row index blank, such as [, 2], R returns all rows for the second column. If you leave the column index blank, such as [1, ], R returns all columns for the first row. You can also use the dollar sign ($) to access a column by its name, which is often faster and more readable than using numeric indices.
Logical indexing allows you to filter data based on conditions. When applying this to a data frame, you can filter rows based on a column value: df[df$age > 21, ]. This is a fundamental way to clean your data by removing outliers or selecting specific groups for analysis. If you encounter an NA (Not Available) value during indexing, R may return NA instead of the value. You can handle this by using the is.na() function to identify and remove missing entries before subsetting.
R Base Functions for Data Manipulation
R base includes a wide array of functions for transforming data without needing external libraries. For basic calculations, you have sum(), mean(), median(), and sd() for standard deviation. These functions often have an na.rm parameter. Setting na.rm = TRUE tells R to ignore missing values; otherwise, any NA in your data will result in the entire calculation returning NA.
To transform data across a vector or a column, the apply family of functions is essential. The apply() function works on matrices or data frames. It takes the data, a margin (1 for rows, 2 for columns), and a function. For instance, apply(my_matrix, 2, mean) calculates the mean of every column. Lapply is used for lists or vectors and always returns a list. Sapply is a simplified version of lapply that attempts to simplify the result into a vector if possible.
The tapply() function is used for grouped summaries. It allows you to apply a function to a numeric vector based on a factor. For example, tapply(df$salary, df$department, mean) provides the average salary for each department. This is the base R alternative to grouping and summarizing. To merge two data frames, use the merge() function, which acts like a SQL join. You specify the columns to join on using the by argument. If the columns have different names in the two frames, use by.x and by.y.
Plotting and Visualization in R Base
The plot() function is the primary tool for visualization in R base. It is a generic function that changes its behavior based on the input. If you provide two numeric vectors, it creates a scatter plot. If you provide a single factor and a numeric vector, it may create a box plot. You can customize the appearance using arguments like col for color, pch for point symbols, and main for the title.
To create a histogram, use hist(). This is useful for understanding the distribution of a single numeric variable. You can adjust the number of bins using the breaks argument. For categorical data, barplot() is the correct choice. Note that barplot() expects a vector of heights, so you often need to use the table() function first to count the occurrences of each category.
Adding elements to an existing plot is done with specific add-on functions. Use lines() to add a line, points() to add more data points, and abline() to add a straight line, such as a regression line or a horizontal mean line. To put multiple plots on one page, use the par(mfrow = c(rows, cols)) command. For example, par(mfrow = c(2, 2)) creates a 2×2 grid of plots. Remember to reset the layout to par(mfrow = c(1, 1)) after you are finished to avoid affecting future plots.
Working with R Base Logic and Loops
Control flow in R base is managed through if-else statements and loops. An if statement executes a block of code only if a condition is true. For multiple conditions, use else if and else. This is typically used for single logical checks during a script’s execution.
For repeating tasks, the for loop is the standard choice. The syntax is for (item in collection) { code }. For example, for (i in 1:10) { print(i) } will print numbers 1 through 10. While for loops are intuitive, they can be slow in R for very large datasets. This is why the apply functions mentioned earlier are preferred for data transformation, as they are often more efficient.
The while loop continues to execute as long as a specific condition remains true. This is useful when you do not know exactly how many iterations are needed, such as in some simulation tasks. To stop a loop prematurely, use the break statement. To skip the current iteration and move to the next, use next. When writing these loops, always ensure the condition will eventually become false to avoid an infinite loop that freezes your session. You can stop a runaway process in most R environments by pressing the Esc key or the Stop button in the console window.
Handling Errors and Checking R Base Results
Debugging is a necessary part of programming. If a script fails, the error message usually points to the line where the problem occurred. You can use the traceback() function immediately after an error to see the sequence of function calls that led to the failure. This helps you identify if the error is in your code or within a nested base function.
To verify that your data manipulation worked, use the head() and tail() functions. These show the first and last six rows of a data frame, allowing you to check for alignment issues or unexpected NAs. The summary() function provides a quick statistical overview of every column, which is a fast way to spot impossible values, such as a negative age or a date in the future.
When you are unsure of how a specific base function works, use the help() function or the question mark shortcut. Typing ?mean in the console opens the documentation for the mean function. The documentation describes the required arguments, the expected input types, and the format of the output. Reading the ‘Examples’ section at the bottom of the help page is often the fastest way to understand how to implement the function in your own code. If the labels in your software interface differ slightly by version, the help documentation remains the definitive source for function syntax.
Related
- CodeHS Cheat Sheet: What It Is and How to Use It
- Cheat Sheet for Exam: How to Make One
- Writing for the Web Cheat Sheet
General information for everyday wellbeing, not medical advice. If something affects your health, sleep or mood for more than a short while, talk to a qualified professional. Read more
Spotted an error? Tell us and we will correct it (corrections policy).