英文:
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 <- 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)
答案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 <- 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
<sup>Created on 2023-06-04 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论