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

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

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:

  1. m1 <- matrix(1:9, nrow = 3, ncol = 3)
  2. m2 <- matrix(1:9, nrow = 3, ncol = 3)
  3. m3 <- matrix(1:9, nrow = 3, ncol = 3)
  4. m_ls <- list(m1,m2,m3)
  5. del <- function(mat){
  6. mat <- mat[,-3]
  7. return(mat)
  8. }
  9. 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:

  1. m1 &lt;- matrix(1:9, nrow = 3, ncol = 3)
  2. m2 &lt;- matrix(1:9, nrow = 3, ncol = 3)
  3. m3 &lt;- matrix(1:9, nrow = 3, ncol = 3)
  4. m_ls &lt;- list(m1,m2,m3)
  5. del &lt;- function(mat){
  6. mat &lt;- mat[,-3]
  7. return(mat)
  8. }
  9. lapply(m_ls, del)

答案1

得分: 4

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

  1. m1 <- m2 <- m3 <- matrix(1:9, nrow = 3, ncol = 3)
  2. m_ls <- list(m1, m2, m3)
  3. lapply(m_ls, `[`, , -3)
  4. #> [[1]]
  5. #> [,1] [,2]
  6. #> [1,] 1 4
  7. #> [2,] 2 5
  8. #> [3,] 3 6
  9. #>
  10. #> [[2]]
  11. #> [,1] [,2]
  12. #> [1,] 1 4
  13. #> [2,] 2 5
  14. #> [3,] 3 6
  15. #>
  16. #> [[3]]
  17. #> [,1] [,2]
  18. #> [1,] 1 4
  19. #> [2,] 2 5
  20. #> [3,] 3 6

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

英文:

You could use [ as a function:

  1. m1 &lt;- m2 &lt;- m3 &lt;- matrix(1:9, nrow = 3, ncol = 3)
  2. m_ls &lt;- list(m1,m2,m3)
  3. lapply(m_ls, `[`, , -3)
  4. #&gt; [[1]]
  5. #&gt; [,1] [,2]
  6. #&gt; [1,] 1 4
  7. #&gt; [2,] 2 5
  8. #&gt; [3,] 3 6
  9. #&gt;
  10. #&gt; [[2]]
  11. #&gt; [,1] [,2]
  12. #&gt; [1,] 1 4
  13. #&gt; [2,] 2 5
  14. #&gt; [3,] 3 6
  15. #&gt;
  16. #&gt; [[3]]
  17. #&gt; [,1] [,2]
  18. #&gt; [1,] 1 4
  19. #&gt; [2,] 2 5
  20. #&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:

确定