使用lapply函数来修改R中的多个矩阵。

huangapple go评论68阅读模式
英文:

use lapply function to modify several matrices in R

问题

I'd like to delete one column (f.e. column 3) from several matrices that are stored in a list.

Can I do this without defining a function?

This is the approach using an own function:

m1 <- matrix(1:9, nrow = 3, ncol = 3)
m2 <- matrix(1:9, nrow = 3, ncol = 3)
m3 <- matrix(1:9, nrow = 3, ncol = 3)
m_ls <- list(m1,m2,m3)

del <- function(mat){
  mat <- mat[,-3]
  return(mat)
}

lapply(m_ls, del)
英文:

I'd like to delete one column (f.e. column 3) from several matrices that are stored in a list.

Can I do this without defining a function?

This is the approach using an own function:

m1 &lt;- matrix(1:9, nrow = 3, ncol = 3)
m2 &lt;- matrix(1:9, nrow = 3, ncol = 3)
m3 &lt;- matrix(1:9, nrow = 3, ncol = 3)
m_ls &lt;- list(m1,m2,m3)

del &lt;- function(mat){
  mat &lt;- mat[,-3]
  return(mat)
}

lapply(m_ls, del)

答案1

得分: 4

你可以使用[作为一个函数:

m1 <- m2 <- m3 <- matrix(1:9, nrow = 3, ncol = 3)
m_ls <- list(m1, m2, m3)

lapply(m_ls, `[`, , -3)
#> [[1]]
#>      [,1] [,2]
#> [1,]    1    4
#> [2,]    2    5
#> [3,]    3    6
#> 
#> [[2]]
#>      [,1] [,2]
#> [1,]    1    4
#> [2,]    2    5
#> [3,]    3    6
#> 
#> [[3]]
#>      [,1] [,2]
#> [1,]    1    4
#> [2,]    2    5
#> [3,]    3    6

创建于2023-06-04,使用reprex v2.0.2

英文:

You could use [ as a function:

m1 &lt;- m2 &lt;- m3 &lt;- matrix(1:9, nrow = 3, ncol = 3)
m_ls &lt;- list(m1,m2,m3)

lapply(m_ls, `[`, , -3)
#&gt; [[1]]
#&gt;      [,1] [,2]
#&gt; [1,]    1    4
#&gt; [2,]    2    5
#&gt; [3,]    3    6
#&gt; 
#&gt; [[2]]
#&gt;      [,1] [,2]
#&gt; [1,]    1    4
#&gt; [2,]    2    5
#&gt; [3,]    3    6
#&gt; 
#&gt; [[3]]
#&gt;      [,1] [,2]
#&gt; [1,]    1    4
#&gt; [2,]    2    5
#&gt; [3,]    3    6

<sup>Created on 2023-06-04 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年6月5日 00:26:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401375.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定