【问题标题】:How to apply different functions to different rows of each matrix in a list?如何将不同的函数应用于列表中每个矩阵的不同行?
【发布时间】:2012-10-23 20:29:17
【问题描述】:

我有一个列表,其中包含几个具有相同行数 (4) 的矩阵。现在我想应用像 log2(row/something) 这样的函数来表示第 1 行和第 4 行,以及像 log2(row/something else) 这样的函数来表示第 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 真的不喜欢这种创造性的解决方案。

【问题讨论】:

    标签: r list function matrix


    【解决方案1】:

    您的第一个解决方案应该可以工作,只是现在该函数只返回最后一部分。稍微改变一下就可以了?

    l<-list(a=matrix(1:16,nrow=4),b=matrix(17:32,nrow=4))
    
    nl <- lapply(l, function(x){
      x[c(1,4),] <- log2(x[c(1,4),]/14)
      x[2:3,] <- log2(x[2:3,]/23)
      return(x)
    })
    

    【讨论】:

    • 哦,太好了。我也玩过类似的解决方案,但我从来没有完全正确。非常感谢!
    • 体面的解决方案——尽管如此,我顺便指出,明智地使用 do.call 和像 myfuncs&lt;-c('my_first_logfunc','mysecond_logfunc') 这样的字符串变量,并且预定义 my_first_logfunc&lt;-function(x) log2(x[c(1,4),]/14) 会更简洁一些。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2011-01-19
    • 2023-03-09
    • 1970-01-01
    相关资源
    最近更新 更多