矢量化!
> dat <- data.frame(c1 = c("abc","dxf","ghi"), c2 = 2:4, w = c(1,0.5,1.5))
实际上,您想要c2 * w
,但我们需要告诉 R 查看数据框内部:
> with(dat, c2 * w)
[1] 2.0 1.5 6.0
dat
我们可以在一行中插入回:
> dat <- within(dat, c3 <- c2 * w)
> dat
c1 c2 w c3
1 abc 2 1.0 2.0
2 dxf 3 0.5 1.5
3 ghi 4 1.5 6.0
(如果要覆盖现有的,请c3
替换为。)c2
c2
如果您有多个除权重之外的数字列,那么如果您想自动化它(即不告诉 R 哪些列要乘以w
),则需要一种稍微不同的策略。
> ## dummy data
> dat2 <- data.frame(c1 = c("abc","dxf","ghi"), c2 = 2:4, w = c(1,0.5,1.5),
c3 = 5:7, c4 = 3:5)
> ## select the columns we want, all numerics, but not `w`
> want <- sapply(dat2, is.numeric) & names(dat2) != "w"
> ## then use want to index into dat2
> dat2[, want] <- with(dat2, dat2[, want] * w)
> dat2
c1 c2 w c3 c4
1 abc 2.0 1.0 5.0 3.0
2 dxf 1.5 0.5 3.0 2.0
3 ghi 6.0 1.5 10.5 7.5