'Multiply without eliminate information

I have a dataframe and I would like to maintain information. My data frame is like:

a <- c("a","b", "c", "d")
b <- c("e","f", "g", "h")
c <- c(1, 2, 1, 3) # multiply
d <- c("AB","BC", "CD", "DE")
e <- c(7, 5, 4, 3)
f<- c(2, 3, 5, 4)
g<- c(5, 7, 7, 9)
h <- c(6, 1, 2, 10)
m <- data.frame(a, b, d, e, f, g, h, c)

I would like to change e and f with the multiply of c * e ... c * h. How can I do it automatically without writing every single column?



Solution 1:[1]

With across:

library(dplyr)
mutate(m, across(c(e, f), ~ .x * c))
#mutate(m, across(c(e, f), `*`, c))
  a b  d  e  f c
1 a e AB  7  2 1
2 b f BC 10  6 2
3 c g CD  4  5 1
4 d h DE  9 12 3

or if you wanna keep the original columns:

mutate(m, across(c(e, f), ~ .x * c, .names = "new_{.col}"))

  a b  d  e  f c new_e new_f
1 a e AB  7  2 1     7     2
2 b f BC 10  6 2    20    12
3 c g CD  4  5 1     4     5
4 d h DE  9 12 3    27    36

or in base R

m[c(4,5)] <- sapply(m[c(4,5)], \(x) c*x)
# or even simpler (as pointed out by @zx8754 in the comments)
#m[, 4:5] <- m[, 4:5] * m$c 

if you wanna keep the original columns:

m[paste0("new_", c("e", "f"))] <- sapply(m[c(4,5)], \(x) c*x)
#m[paste0("new_", c("e", "f"))] <- m[, 4:5] * m$c 

Solution 2:[2]

You could use mutate, e.g.

a <- c("a","b", "c", "d")
b <- c("e","f", "g", "h")
c <- c(1, 2, 1, 3) #multiply
d <- c("AB","BC", "CD", "DE")
e <- c(7, 5, 4, 3)
f<- c(2, 3, 5, 4)
m <- data.frame(a, b, d, e, f, c)

library(dplyr)
m %>% 
  mutate(e = e*c,
         f = f*c)

Output:

  a b  d  e  f c
1 a e AB  7  2 1
2 b f BC 10  6 2
3 c g CD  4  5 1
4 d h DE  9 12 3

Solution 3:[3]

base R solution:

m[,4:5] <- sapply(m[4:5], "*", c)
m
  a b  d  e  f c
1 a e AB  7  2 1
2 b f BC 10  6 2
3 c g CD  4  5 1
4 d h DE  9 12 3

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Julian
Solution 3 TarJae