乘而不消信息

Multiply without eliminate information

我有一个数据框,我想维护信息。我的数据框是这样的:

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)

我想用 c * e ... c * h 的乘积来改变 e 和 f。如何在不编写每一列的情况下自动执行此操作?

您可以使用 mutate,例如

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)

输出:

  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

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

或者如果您想保留原始列:

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

或以 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 

如果您想保留原始列:

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 

基础 R 解决方案:

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