Charlon16
Charlon16

Reputation: 3

Multiplying One column with others in R

hope everything is doing well.

I'm stuck trying to multiply one column with others.

A Mult1 Mult2 Mult3
1 2 3 4
2 3 4 6
2 1 4 5

I want to create a new columns named MultA1, MultA2, MultA3 this way

MultA1 MultA2 MultA3
2 3 4
6 8 12
2 8 10

Is there an easy way to do it for many columns?

Thank you!

Upvotes: 0

Views: 70

Answers (4)

akrun
akrun

Reputation: 887028

Using startsWith from base R

i1 <- startsWith(names(df), 'Mult')
df[paste0(names(df)[i1], "A")] <- df[i1] * df$A

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 388862

Multiply A to all the 'Mult' columns directly.

cols <- grep('Mult', names(df), value = TRUE)
df[paste0(cols, 'A')] <- df$A * df[cols]
df

#  A Mult1 Mult2 Mult3 Mult1A Mult2A Mult3A
#1 1     2     3     4      2      3      4
#2 2     3     4     6      6      8     12
#3 2     1     4     5      2      8     10

data

df <- data.frame(A = c(1, 2, 2), Mult1 = c(2, 3, 1), 
                 Mult2 = c(3, 4, 4), Mult3 = c(4, 6, 5))

Upvotes: 1

TimTeaFan
TimTeaFan

Reputation: 18551

We can use dplyr::across for this:

library(dplyr)

df <- data.frame(
  A = 1:3,
  Mult1 = 2:4,
  Mult2 = 3:5,
  Mult3 = 4:6
)

df %>% 
  mutate(across(starts_with("Mult"),
                ~ A * .x,
                .names = "{.col}A"))

#>   A Mult1 Mult2 Mult3 Mult1A Mult2A Mult3A
#> 1 1     2     3     4      2      3      4
#> 2 2     3     4     5      6      8     10
#> 3 3     4     5     6     12     15     18

Created on 2021-04-10 by the reprex package (v0.3.0)

Upvotes: 2

Chris Ruehlemann
Chris Ruehlemann

Reputation: 21400

Here's an easy dplyrapproach:

library(dplyr)
df %>%
  mutate(
    MultA1 = A*Mult1,
    MultA2 = A*Mult2,
    MultA3 = A*Mult3
  ) %>%
  select(-c(1:4))
  MultA1 MultA2 MultA3
1      2      3      4
2      6      8     10
3     12     15     18

A base R approach with lapply is this:

df[paste0("MultA", 1:3)] <- lapply(df[2:4], function(x) x*df$A)
df[,1:4] <- NULL                                   # remove the original four columns

Data:

df <- data.frame(
  A = 1:3,
  Mult1 = 2:4,
  Mult2 = 3:5,
  Mult3 = 4:6
)

Upvotes: 1

Related Questions