0
我有一個列表包含相同數量的行(4)的幾個矩陣。現在,我想申請一個功能類似的log 2(行/某事)說行1和4類似的log 2(行/別的東西)的功能,行2和3如何將不同的函數應用於列表中每個矩陣的不同行?
在代碼:
# Create list with 2 matrices with 4 rows
l<-list(a=matrix(1:16,nrow=4),b=matrix(17:32,nrow=4))
# Now I thought it might be possible to
nl <- lapply(l, function(x){
log2(x[c(1,4),]/14)
log2(x[2:3,]/23)
})
但結果是隻有lapply
中的最後一個函數被執行。此外,我認爲它可能是:
nl <- l
lapply(nl, function(x) x[c(1,4),]) <- lapply(l, function(x) log2(x[c(1,4),]/14))
lapply(nl, function(x) x[2:3,]) <- lapply(l, function(x) log2(x[2:3,]/23))
但R真的不喜歡那個創造性的解決方案。
哦,太好了。我也玩過一個類似的解決方案,但我從來沒有這樣做過。爲此非常感謝! – Pascal
體面的解決方案 - 我注意到,明智地使用了'do.call'和一個字符串變量,如'myfuncs <-c('my_first_logfunc','mysecond_logfunc')',並且預定義了'my_first_logfunc <-function(x )log2(x [c(1,4),]/14)'會更清潔一些。 –