您也可以使用lapply
這樣
setNames(data.frame(lapply(head(seq_along(df), -1), function(i) df[, i] * (i < df$ZeroMth))),
head(names(df), -1))
which returns
Mth1 Mth2 Mth3 Mth4
1 0 0 0 0
2 3 3 0 0
3 4 0 0 0
4 1 2 2 0
5 2 2 0 0
在這裏,您將遍歷月份矢量的位置,並檢查月份中的元素是否小於指定的零月份。如果是,則返回該值,否則爲0. setNames
用於恢復變量名稱。
一些基準
測試後,改變比2X加速更lapply
到sapply
結果。主要的放緩是由於轉換爲data.frame。
這讓我進一步檢查了一下。這裏是微基準結果。
microbenchmark(
db.mat=t(apply(X = df, MARGIN = 1, function(x)
replace(x = x, list = x[NCOL(df)]:(NCOL(df)-1), values = 0))),
db.df=data.frame(t(apply(X = df, MARGIN = 1, function(x)
replace(x = x, list = x[NCOL(df)]:(NCOL(df)-1), values = 0)))),
lmo.list=setNames(lapply(head(seq_along(df), -1),
function(i) df[, i] * (i < df$ZeroMth)),
head(names(df), -1)),
lmo.dfl=setNames(data.frame(lapply(head(seq_along(df), -1),
function(i) df[, i] * (i < df$ZeroMth))),
head(names(df), -1)),
lmo.dfs=setNames(data.frame(sapply(head(seq_along(df), -1),
function(i) df[, i] * (i < df$ZeroMth))),
head(names(df), -1)),
lmo.listAlt=setNames(lapply(head(seq_along(df), -1),
function(i) {temp <- df[, i]; temp[i < df$ZeroMth] <- 0; temp}),
head(names(df), -1)),
lmo.dflAlt=setNames(data.frame(lapply(head(seq_along(df), -1),
function(i) {temp <- df[, i]; temp[i < df$ZeroMth] <- 0; temp})),
head(names(df), -1)),
lmo.dfsAlt=setNames(data.frame(sapply(head(seq_along(df), -1),
function(i) {temp <- df[, i]; temp[i < df$ZeroMth] <- 0; temp})),
head(names(df), -1)))
Unit: microseconds
expr min lq mean median uq max neval cld
df.mat 135.994 155.2380 161.2480 159.6570 166.785 196.436 100 b
db.df 225.231 236.9190 248.3295 246.0430 256.164 340.411 100 c
lmo.list 84.960 99.5005 105.8299 104.9175 110.905 156.806 100 a
lmo.dfl 439.057 459.1565 480.3425 476.5475 492.656 647.751 100 d
lmo.dfs 173.057 187.3120 217.2876 195.8650 202.850 2257.151 100 c
lmo.listAlt 91.803 108.0535 114.6253 113.1860 118.602 185.602 100 ab
lmo.dflAlt 458.158 481.2520 521.6052 498.2155 516.462 2584.163 100 d
lmo.dfsAlt 181.610 198.4310 221.5613 204.2755 212.686 1611.395 100 c
哇,lapply
與data.frame
是超級慢。
感謝#d.b使這個緊湊。我花了數小時試圖在幾秒鐘內獲得您提供的解決方案! –