是否可以使用lappy而不是for cycle更改列表中数组的维度名称?
我有一个n维数组的大列表,所有数组的维数都相同。 我需要设置或更改列表中所有数组中特定维度的名称。 为了说明这一点,我举了一个玩具示例,如下所示:是否可以使用lappy而不是for cycle更改列表中数组的维度名称?,r,R,我有一个n维数组的大列表,所有数组的维数都相同。 我需要设置或更改列表中所有数组中特定维度的名称。 为了说明这一点,我举了一个玩具示例,如下所示: a1 <- matrix(1:6, ncol = 2) a2 <- a1*10 (l1 <- list(a1, a2)) ## [[1]] ## [,1] [,2] ## [1,] 1 4 ## [2,] 2 5 ## [3,] 3 6 ## ## [[2]] ## [,1]
a1 <- matrix(1:6, ncol = 2)
a2 <- a1*10
(l1 <- list(a1, a2))
## [[1]]
## [,1] [,2]
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6
##
## [[2]]
## [,1] [,2]
## [1,] 10 40
## [2,] 20 50
## [3,] 30 60
例如,我想在两个数组中将列命名为1和2。我
要知道,使用循环进行此操作很容易
for (i in 1:length(l1)) {
dimnames(l1[[i]])[[2]] <- c("one", "two")
}
l1
## [[1]]
## one two
## [1,] 1 4
## [2,] 2 5
## [3,] 3 6
##
## [[2]]
## one two
## [1,] 10 40
## [2,] 20 50
## [3,] 30 60
您是否知道,使用上的lappy函数是否可能得到相同的结果
列表l1?返回是一个键
l1_2 <- lapply(l1, function(x) {
dimnames(x)[[2]] <- c("one", "two")
return(x)
})
返回是一把钥匙
l1_2 <- lapply(l1, function(x) {
dimnames(x)[[2]] <- c("one", "two")
return(x)
})
您可以更改矩阵的列名称
lapply(l1, function(x) {colnames(x) <- c('one', 'two');x})
#[[1]]
# one two
#[1,] 1 4
#[2,] 2 5
#[3,] 3 6
#[[2]]
# one two
#[1,] 10 40
#[2,] 20 50
#[3,] 30 60
您可以更改矩阵的列名称
lapply(l1, function(x) {colnames(x) <- c('one', 'two');x})
#[[1]]
# one two
#[1,] 1 4
#[2,] 2 5
#[3,] 3 6
#[[2]]
# one two
#[1,] 10 40
#[2,] 20 50
#[3,] 30 60