Apply a Function (or functions) across Multiple Columns using dplyr in R
Last Updated :
23 Jul, 2025
Data processing and manipulation are one of the core tasks in data science and machine learning. R Programming Language is one of the widely used programming languages for data science, and dplyr package is one of the most popular packages in R for data manipulation. In this article, we will learn how to apply a function (or functions) across multiple columns in R using the dplyr package.
What is dplyr?
dplyr is a powerful and efficient data manipulation package in R. It provides a set of functions for filtering, grouping, and transforming data. The functions in dplyr are designed to be simple and intuitive, making it easy to perform complex data manipulations with a few lines of code.
Prerequisites
Before we start, make sure that you have dplyr package installed in your system. If not, install it by running the following code:
install.packages("dplyr")
Once you have dplyr installed, you can load it into your R environment by running the following code:
library(dplyr)
Applying a Function to a Single Column
Let's start by applying a function to a single column. For this, we will use the built-in mtcars data set. You can load this data set by running the following code. The mtcars data set contains information about various car models, including their miles per gallon (mpg) ratings. Let's say we want to calculate the logarithm of the mpg column. We can do this using the mutate function from the dplyr package.
R
data("mtcars")
mtcars_log_mpg <- mtcars %>%
mutate(log_mpg = log(mpg))
The mutate function takes the data frame mtcars as input and adds a new column log_mpg with the logarithm of the mpg column. The %>% operator is the pipe operator, which passes the output of the previous operation as the first argument to the next operation.
Let's visualize the changes brought by this transformation using a bar plot:
R
par(mfrow=c(1,2))
barplot(mtcars$mpg, main="Original mpg")
barplot(mtcars_log_mpg$log_mpg, main="log(mpg)")
OUTPUT:
\
This bar plot shows the original mpg column and its logarithm side by side, which helps us understand the changes brought by the logarithm function.
As we can see, the logarithm function reduces the range of values, which can be useful in some cases where the original values have a large range. In this case, the logarithm function brings the values of the mpg column closer to each other, which can make it easier to see patterns and relationships in the data.
Applying a Function to Multiple Columns
In the previous section, we learned how to apply a function to a single column. But what if we want to apply the same function to multiple columns in a data frame? For this, we can use the mutate_all function from the dplyr package. The mutate_all function takes a data frame as input and applies a function to all columns.Let's say we have a data frame df with three columns, and we want to apply the logarithm function to all columns.
The mutate_all function applies the logarithm function to all columns in the data frame and returns a new data frame with the same number of columns, but with the logarithm of each column. To visually represent the changes brought by applying the logarithm function to all columns, we can plot the original data and the transformed data side by side:
R
df <- data.frame(col1 = runif(10),
col2 = runif(10),
col3 = runif(10))
df_log <- df %>% mutate_all(~ log(.))
par(mfrow=c(3,2))
for (i in 1:ncol(df)) {
barplot(df[,i], main=colnames(df)[i])
barplot(df_log[,i],
main=paste("log(", colnames(df)[i], ")"))
}
Output:
Barplot for the data after applying log transformations
In this example, the original data is plotted in the first column of each row, and the transformed data is plotted in the second column of each row. The plots show how the logarithm function changes the distribution of each column.
Applying Different Functions to Different Columns
Sometimes, we may want to apply different functions to different columns. For this, we can use the mutate_at function from the dplyr package. The mutate_at function takes two arguments: the first is a vector of column names or indices, and the second is a formula that specifies the function to be applied.
Let's say we want to apply the logarithm function to the first and third columns, and the square root function to the second column. Here, the mutate_at function is used twice, once for applying the logarithm function to columns 1 and 3, and once for applying the square root function to column 2. We can plot each column of the original data frame, its logarithm, and its square root:
R
df_log_sqrt <- df %>%
mutate_at(c(1, 3), ~ log(.)) %>%
mutate_at(2, ~ sqrt(.))
par(mfrow=c(3,3))
for (i in 1:ncol(df)) {
barplot(df[,i], main=colnames(df)[i])
barplot(df_log_sqrt[,i],
main=ifelse(i %in% c(1,3),
paste("log(", colnames(df)[i], ")"),
paste("sqrt(", colnames(df)[i], ")")))
}
OUTPUT:
Barplot for the data after applying s square root transformations
As we can see, the first and third columns are transformed by the logarithm function, while the second column is transformed by the square root function.
Using everything() and across() function
Let's use the iris dataset as an example, and suppose we want to round all the numerical columns to the nearest integer. We can do this as follows:
R
library(dplyr)
# Select only numeric columns
iris_num <- iris %>%
select(where(is.numeric))
# Apply the round function to each numeric column
iris_rounded <- iris_num %>%
mutate(across(everything(), ~ round(., 0)))
In the above code, the mutate() function is used to apply the round() function to every column using across(). The everything() function is used as the argument to across() to apply the function to all columns. The second argument to round() is 0, which will round each data point to the nearest integer.
The resulting dataset iris_rounded will contain the same columns as iris_num, but with each data, point rounded to the nearest integer.
Using c_across() function
c_across() is a function in the dplyr package in R that allows you to select columns in a tidy-select manner and apply the same function to them. It is commonly used in conjunction with rowwise() to apply functions row-wise to a data frame. c_across() takes a tidy-select object (a set of columns that you want to apply a function too) and returns a list of the output of applying a function to each column.
R
library(dplyr)
# create sample data frame
df <- tibble(id = 1:3, a = c(1, 2, 3),
b = c(4, 5, 6), c = c(7, 8, 9))
# use rowwise() and c_across()
# to get sum of selected columns
df %>%
rowwise() %>%
mutate(
sum_cols = sum(c_across(c(a, c)))
)
Output:
# A tibble: 3 × 5
# Rowwise:
id a b c sum_cols
<int> <dbl> <dbl> <dbl> <dbl>
1 1 1 4 7 8
2 2 2 5 8 10
3 3 3 6 9 12
In the above example, c_across() is used to select columns 'a' and 'c', and rowwise() is used to perform row-wise operations on the selected columns. The mutate() function is used to create a new column named sum_cols, which contains the sum of values in columns 'a' and 'c'.
Using starts_with(), ends_with()
starts_with() returns a logical vector indicating which columns' names start with a particular string.
R
# Example dataset
df <- tibble(a_col = 1:3,
b_col = 4:6, c_col = 7:9)
# Select columns that start with 'a'
df_starts_with_a <- df %>%
select(starts_with('a'))
print(df_starts_with_a)
Output:
# A tibble: 3 × 1
a_col
<int>
1 1
2 2
3 3
ends_with() returns a logical vector indicating which column names end with a particular string.
R
# Example dataset
df <- tibble(a_col_1 = 1:3,
b_col_0 = 4:6, c_col_1 = 7:9)
# Select columns that end with '_1'
df_ends_with_1 <- df %>%
select(ends_with('_1'))
print(df_ends_with_1)
Output:
# A tibble: 3 × 2
a_col_1 c_col_1
<int> <int>
1 1 7
2 2 8
3 3 9
Using if_any() and if_all()
if_any() and if_all() also return a logical vector indicating whether any of the selected columns meet the specified condition. In the below example, the if_all() function filters rows where all of the selected columns have values greater than 7.9.
R
library(dplyr)
# Filter rows where all the selected
# columns have values greater than 20
mtcars %>%
filter(if_all(c("mpg", "cyl", "disp"),
~. > 7.9))
Output:
mpg cyl disp hp drat wt qsec vs am gear carb
Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 0 0 3 2
Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 0 0 3 4
Merc 450SE 16.4 8 275.8 180 3.07 4.070 17.40 0 0 3 3
Merc 450SL 17.3 8 275.8 180 3.07 3.730 17.60 0 0 3 3
Merc 450SLC 15.2 8 275.8 180 3.07 3.780 18.00 0 0 3 3
Cadillac Fleetwood 10.4 8 472.0 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460.0 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440.0 230 3.23 5.345 17.42 0 0 3 4
Dodge Challenger 15.5 8 318.0 150 2.76 3.520 16.87 0 0 3 2
AMC Javelin 15.2 8 304.0 150 3.15 3.435 17.30 0 0 3 2
Camaro Z28 13.3 8 350.0 245 3.73 3.840 15.41 0 0 3 4
Pontiac Firebird 19.2 8 400.0 175 3.08 3.845 17.05 0 0 3 2
Ford Pantera L 15.8 8 351.0 264 4.22 3.170 14.50 0 1 5 4
Maserati Bora 15.0 8 301.0 335 3.54 3.570 14.60 0 1 5 8
Example 2:
The if_any() function filters rows where any of the selected columns have values greater than 400.
R
library(dplyr)
# Filter rows where any of the selected
# columns have values greater than 200
mtcars %>%
filter(if_any(c("mpg", "cyl", "disp"),
~. > 400))
Output:
mpg cyl disp hp drat wt qsec vs am gear carb
Cadillac Fleetwood 10.4 8 472 205 2.93 5.250 17.98 0 0 3 4
Lincoln Continental 10.4 8 460 215 3.00 5.424 17.82 0 0 3 4
Chrysler Imperial 14.7 8 440 230 3.23 5.345 17.42 0 0 3 4
Conclusion
In this article, we have explored several functions in the dplyr package that can be used to apply functions across multiple columns in R. The mutate function is used to apply a function to a single column, while the mutate_all function can be used to apply the same function to all columns. The mutate_at function can be used to apply different functions to different columns.
The cross function is a powerful addition to the dplyr package, allowing you to apply a function to multiple columns using column selection helpers like starts_with() and ends_with(). The c_across() function can be used to select a subset of columns and apply a function to them. The everything() function selects all columns.
Furthermore, the if_any() and if_all() functions in combination with the above-mentioned functions allow for the conditional application of functions. These functions can make complex data manipulations much easier and more efficient.
In conclusion, the dplyr package provides a powerful set of tools for data manipulation in R. By using these functions, you can easily apply functions to multiple columns and perform complex data manipulations with ease.
Similar Reads
R Tutorial | Learn R Programming Language R is an interpreted programming language widely used for statistical computing, data analysis and visualization. R language is open-source with large community support. R provides structured approach to data manipulation, along with decent libraries and packages like Dplyr, Ggplot2, shiny, Janitor a
4 min read
Introduction
R Programming Language - IntroductionR is a programming language and software environment that has become the first choice for statistical computing and data analysis. Developed in the early 1990s by Ross Ihaka and Robert Gentleman, R was built to simplify complex data manipulation and create clear, customizable visualizations. Over ti
4 min read
Interesting Facts about R Programming LanguageR is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge to
4 min read
R vs PythonR Programming Language and Python are both used extensively for Data Science. Both are very useful and open-source languages as well. For data analysis, statistical computing, and machine learning Both languages are strong tools with sizable communities and huge libraries for data science jobs. A th
5 min read
Environments in R ProgrammingThe environment is a virtual space that is triggered when an interpreter of a programming language is launched. Simply, the environment is a collection of all the objects, variables, and functions. Or, Environment can be assumed as a top-level object that contains the set of names/variables associat
3 min read
Introduction to R StudioR Studio is an integrated development environment(IDE) for R. IDE is a GUI, where we can write your quotes, see the results and also see the variables that are generated during the course of programming. R Studio is available as both Open source and Commercial software.R Studio is also available as
4 min read
How to Install R and R Studio?Installing R and RStudio is the first step to working with R for data analysis, statistical modeling, and visualizations. This article will guide you through the installation process on both Windows and Ubuntu operating systemsWhy use R Studio? RStudio is an open-source integrated development enviro
4 min read
Creation and Execution of R File in R StudioR Studio is an integrated development environment (IDE) for R. IDE is a GUI, where you can write your quotes, see the results and also see the variables that are generated during the course of programming. R is available as an Open Source software for Client as well as Server Versions. 1. Creating a
5 min read
Clear the Console and the Environment in R StudioR Studio is an integrated development environment(IDE) for R. IDE is a GUI, where you can write your quotes, see the results and also see the variables that are generated during the course of programming. Clearing the Console We Clear console in R and RStudio, In some cases when you run the codes us
2 min read
Hello World in R ProgrammingWhen we start to learn any programming languages we do follow a tradition to begin HelloWorld as our first basic program. Here we are going to learn that tradition. An interesting thing about R programming is that we can get our things done with very little code. Before we start to learn to code, le
2 min read
Fundamentals of R
Basic Syntax in R ProgrammingR is the most popular language used for Statistical Computing and Data Analysis with the support of over 10, 000+ free packages in CRAN repository. Like any other programming language, R has a specific syntax which is important to understand if you want to make use of its features. This article assu
3 min read
Comments in RIn R Programming Language, Comments are general English statements that are typically written in a program to describe what it does or what a piece of code is designed to perform. More precisely, information that should interest the coder and has nothing to do with the logic of the code. They are co
3 min read
R-OperatorsOperators are the symbols directing the compiler to perform various kinds of operations between the operands. Operators simulate the various mathematical, logical, and decision operations performed on a set of Complex Numbers, Integers, and Numericals as input operands. R supports majorly four kinds
5 min read
R-KeywordsR keywords are reserved words that have special meaning in the language. They help control program flow, define functions, and represent special values. We can check for which words are keywords by using the help(reserved) or ?reserved function.Rhelp(reserved) # or "?reserved"Output:Reserved Key Wor
2 min read
R-Data TypesData types in R define the kind of values that variables can hold. Choosing the right data type helps optimize memory usage and computation. Unlike some languages, R does not require explicit data type declarations while variables can change their type dynamically during execution.R Programming lang
5 min read
Variables
R Variables - Creating, Naming and Using Variables in RA variable is a memory location reserved for storing data, and the name assigned to it is used to access and manipulate the stored data. The variable name is an identifier for the allocated memory block, which can hold values of various data types during the programâs execution.In R, variables are d
5 min read
Scope of Variable in RIn R, variables are the containers for storing data values. They are reference, or pointers, to an object in memory which means that whenever a variable is assigned to an instance, it gets mapped to that instance. A variable in R can store a vector, a group of vectors or a combination of many R obje
5 min read
Dynamic Scoping in R ProgrammingR is an open-source programming language that is widely used as a statistical software and data analysis tool. R generally comes with the Command-line interface. R is available across widely used platforms like Windows, Linux, and macOS. Also, the R programming language is the latest cutting-edge to
5 min read
Lexical Scoping in R ProgrammingLexical scoping means R decides where to look for a variable based on where the function was written (defined), not where it is called.When a function runs and it sees a variable, R checks:Inside the function, is the variable there?If not, it looks in the environment where the function was created.T
4 min read
Input/Output
Control Flow
Control Statements in R ProgrammingControl statements are expressions used to control the execution and flow of the program based on the conditions provided in the statements. These structures are used to make a decision after assessing the variable. In this article, we'll discuss all the control statements with the examples. In R pr
4 min read
Decision Making in R Programming - if, if-else, if-else-if ladder, nested if-else, and switchDecision making in programming allows us to control the flow of execution based on specific conditions. In R, various decision-making structures help us execute statements conditionally. These include:if statementif-else statementif-else-if laddernested if-else statementswitch statement1. if Stateme
3 min read
Switch case in RSwitch case statements are a substitute for long if statements that compare a variable to several integral values. Switch case in R is a multiway branch statement. It allows a variable to be tested for equality against a list of values. Switch statement follows the approach of mapping and searching
2 min read
For loop in RFor loop in R Programming Language is useful to iterate over the elements of a list, data frame, vector, matrix, or any other object. It means the for loop can be used to execute a group of statements repeatedly depending upon the number of elements in the object. It is an entry-controlled loop, in
5 min read
R - while loopWhile loop in R programming language is used when the exact number of iterations of a loop is not known beforehand. It executes the same code again and again until a stop condition is met. While loop checks for the condition to be true or false n+1 times rather than n times. This is because the whil
5 min read
R - Repeat loopRepeat loop in R is used to iterate over a block of code multiple number of times. And also it executes the same code again and again until a break statement is found. Repeat loop, unlike other loops, doesn't use a condition to exit the loop instead it looks for a break statement that executes if a
2 min read
goto statement in R ProgrammingGoto statement in a general programming sense is a command that takes the code to the specified line or block of code provided to it. This is helpful when the need is to jump from one programming section to the other without the use of functions and without creating an abnormal shift. Unfortunately,
2 min read
Break and Next statements in RIn R Programming Language, we require a control structure to run a block of code multiple times. Loops come in the class of the most fundamental and strong programming concepts. A loop is a control statement that allows multiple executions of a statement or a set of statements. The word âloopingâ me
3 min read
Functions
Functions in R ProgrammingA function accepts input arguments and produces the output by executing valid R commands that are inside the function. Functions are useful when we want to perform a certain task multiple times.In R Programming Language when we are creating a function the function name and the file in which we are c
5 min read
Function Arguments in R ProgrammingArguments are the parameters provided to a function to perform operations in a programming language. In R programming, we can use as many arguments as we want and are separated by a comma. There is no limit on the number of arguments in a function in R. In this article, we'll discuss different ways
4 min read
Types of Functions in R ProgrammingA function is a set of statements orchestrated together to perform a specific operation. A function is an object so the interpreter is able to pass control to the function, along with arguments that may be necessary for the function to accomplish the actions. The function in turn performs the task a
6 min read
Recursive Functions in R ProgrammingRecursion, in the simplest terms, is a type of looping technique. It exploits the basic working of functions in R. Recursive Function in R: Recursion is when the function calls itself. This forms a loop, where every time the function is called, it calls itself again and again and this technique is
4 min read
Conversion Functions in R ProgrammingSometimes to analyze data using R, we need to convert data into another data type. As we know R has the following data types Numeric, Integer, Logical, Character, etc. similarly R has various conversion functions that are used to convert the data type. In R, Conversion Function are of two types: Con
4 min read
Data Structures
Data Structures in R ProgrammingA data structure is a particular way of organizing data in a computer so that it can be used effectively. The idea is to reduce the space and time complexities of different tasks. Data structures in R programming are tools for holding multiple values. Râs base data structures are often organized by
4 min read
R StringsStrings are a bunch of character variables. It is a one-dimensional array of characters. One or more characters enclosed in a pair of matching single or double quotes can be considered a string in R. It represents textual content and can contain numbers, spaces, and special characters. An empty stri
6 min read
R-VectorsR Vectors are the same as the arrays in R language which are used to hold multiple data values of the same type. One major key point is that in R Programming Language the indexing of the vector will start from '1' and not from '0'. We can create numeric vectors and character vectors as well. R - Vec
4 min read
R-ListsA list in R programming is a generic object consisting of an ordered collection of objects. Lists are one-dimensional, heterogeneous data structures. The list can be a list of vectors, a list of matrices, a list of characters, a list of functions, and so on. A list in R is created with the use of th
6 min read
R - ArrayArrays are important data storage structures defined by a fixed number of dimensions. Arrays are used for the allocation of space at contiguous memory locations.In R Programming Language Uni-dimensional arrays are called vectors with the length being their only dimension. Two-dimensional arrays are
7 min read
R-MatricesR-matrix is a two-dimensional arrangement of data in rows and columns. In a matrix, rows are the ones that run horizontally and columns are the ones that run vertically. In R programming, matrices are two-dimensional, homogeneous data structures. These are some examples of matrices:R - MatricesCreat
10 min read
R-FactorsFactors in R Programming Language are used to represent categorical data, such as "male" or "female" for gender. While they might seem similar to character vectors, factors are actually stored as integers with corresponding labels. Factors are useful when dealing with data that has a fixed set of po
4 min read
R-Data FramesR Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R that are used to store tabular data. Data frames can also be interpreted as matrices where each column of a matr
6 min read
Object Oriented Programming
R-Object Oriented ProgrammingIn R, Object-Oriented Programming (OOP) uses classes and objects to manage program complexity. R is a functional language that applies OOP concepts. Class is like a car's blueprint, detailing its model, engine and other features. Based on this blueprint, we select a car, which is the object. Each ca
7 min read
Classes in R ProgrammingClasses and Objects are core concepts in Object-Oriented Programming (OOP), modeled after real-world entities. In R, everything is treated as an object. An object is a data structure with defined attributes and methods. A class is a blueprint that defines a set of properties and methods shared by al
3 min read
R-ObjectsIn R programming, objects are the fundamental data structures used to store and manipulate data. Objects in R can hold different types of data, such as numbers, characters, lists, or even more complex structures like data frames and matrices.An object in R is important an instance of a class and can
3 min read
Encapsulation in R ProgrammingEncapsulation is the practice of bundling data (attributes) and the methods that manipulate the data into a single unit (class). It also hides the internal state of an object from external interference and unauthorized access. Only specific methods are allowed to interact with the object's state, en
3 min read
Polymorphism in R ProgrammingR language implements parametric polymorphism, which means that methods in R refer to functions, not classes. Parametric polymorphism primarily lets us define a generic method or function for types of objects we havenât yet defined and may never do. This means that one can use the same name for seve
6 min read
R - InheritanceInheritance is one of the concept in object oriented programming by which new classes can derived from existing or base classes helping in re-usability of code. Derived classes can be the same as a base class or can have extended features which creates a hierarchical structure of classes in the prog
7 min read
Abstraction in R ProgrammingAbstraction refers to the process of simplifying complex systems by concealing their internal workings and only exposing the relevant details to the user. It helps in reducing complexity and allows the programmer to work with high-level concepts without worrying about the implementation.In R, abstra
3 min read
Looping over Objects in R ProgrammingOne of the biggest issues with the âforâ loop is its memory consumption and its slowness in executing a repetitive task. When it comes to dealing with a large data set and iterating over it, a for loop is not advised. In this article we will discuss How to loop over a list in R Programming Language
5 min read
S3 class in R ProgrammingAll things in the R language are considered objects. Objects have attributes and the most common attribute related to an object is class. The command class is used to define a class of an object or learn about the classes of an object. Class is a vector and this property allows two things:  Objects
8 min read
Explicit Coercion in R ProgrammingCoercing of an object from one type of class to another is known as explicit coercion. It is achieved through some functions which are similar to the base functions. But they differ from base functions as they are not generic and hence do not call S3 class methods for conversion. Difference between
3 min read
Error Handling