Vectorise!
> 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
(如果要覆蓋現有的01,請將c3
替換爲。)
如果除了權重以外還有多個數字列,那麼如果要自動執行它,則需要一個簡單的策略。不告訴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
這看起來很棒! – speendo 2011-02-23 14:27:04
優秀的技術提取數字列,然後重新插入它們。謝謝! – drbv 2012-09-12 19:09:44