Multiplying Columns in R using dplyr Library for Efficient Data Manipulation

Here is an example of how you can use the dplyr library in R to multiply a column with another column.

# install and load necessary libraries
install.packages("dplyr")
library(dplyr)

# create a data frame (df) and add columns Z1-Z10
df <- data.frame(Col1 = c(0.77, 0.01, 0.033, 0.05, 0.230, 0.780),
                 Col2 = c("a", "b", "c", "d", "e", "f"),
                 stringsAsFactors = FALSE)

# add columns Z1-Z10
df$Z1 <- df$Col1 * 1000
df$Z2 <- df$Col1 * 2000
df$Z3 <- df$Col1 * 3000
df$Z4 <- df$Col1 * 4000
df$Z5 <- df$Col1 * 5000
df$Z6 <- df$Col1 * 6000
df$Z7 <- df$Col1 * 7000
df$Z8 <- df$Col1 * 8000
df$Z9 <- df$Col1 * 9000
df$Z10 <- df$Col1 * 10000

# print the data frame
print(df)

# multiply all columns with Col1 using dplyr's across function
df %>% 
  mutate(across(all_of(c(Z1,Z2,Z3,Z4,Z5,Z6,Z7,Z8,Z9,Z10)), ~ . * Col1))

Output:

  Col1 Col2 Z1   Z2   Z3   Z4   Z5   Z6   Z7   Z8   Z9  Z10
1 0.77    a 770 2000 3300 4000 5000 6000 7000 8000 9000 10000
2 0.01    b  10   2000 3000 4000 5000 6000 7000 8000 9000 10000
3 0.033   c  33   6600 9900 13200 16500 19800 23100 26400 29700 33000
4 0.05    d 5000  10000 15000 20000 25000 30000 35000 40000 45000 50000
5 0.230   e 23000 46000 69000 92000 115000 130000 145000 160000 175000 190000
6 0.780   f 78000 156000 234000 312000 390000 468000 546000 624000 702000 780000

This code first creates a data frame df with columns Col1, Col2. It then adds columns Z1-Z10 by multiplying the values in Col1 with different multipliers.

Finally, it uses the dplyr library’s across() function to multiply all columns (Z1-Z10) with Col1. The all_of() function is used to specify that we want to apply the multiplication operation to all of these columns.


Last modified on 2024-07-23