2017-05-28 44 views
0

我今天开始使用R,所以如果这太基本了,我很抱歉。循环遍历向量中的元素,并且元素是矩阵

首先我构造2个矩阵,并构造一个向量,其条目是这些矩阵。然后,我尝试循环向量的元素,即矩阵。但是,当我这样做时,我会得到一个“长度为零的参数”错误。

cam <- 1:12 
ped <- 13:24 

dim(cam) <- c(3,4) 
dim(ped) <- c(4,3) 

mats <- c('cam','ped') 

for (i in 1:2) { 
    rownames(mats[i]) <- LETTERS[1:dim(mats[i])[1]] 
    colnames(mats[i]) <- LETTERS[1:dim(mats[i])[2]] 
} 

错误文本如下:

Error in 1:dim(mats[i])[1] : argument of length 0 

的问题是:如何循环一个矢量的元素,这些元素的矩阵? (我猜我没有正确地调用元素)。感谢您的耐心。

回答

2

去到在R选项是使用列表:

cam <- 1:12 ; dim(cam) <- c(3,4) 
# same as matrix(1:12, nrow = 3, ncol = 4) 
ped <- 13:24 ; dim(ped) <- c(4,3) 

# save the list ('=' sign for naming purposes only here) 
mats <- list(cam = cam, ped = ped) 

# notice the double brackets '[[' which is used for picking the list 
for (i in 1:length(mats) { 
    rownames(mats[[i]]) <- LETTERS[1:dim(mats[[i]])[1]] 
    colnames(mats[[i]]) <- LETTERS[1:dim(mats[[i]])[2]] 
} 

# finally you can call the whole list at once as follows: 
mats 
# or seperately using $ or [[ 
mats$cam # mats[['cam']] 
mats$ped # mats[['ped']] 

或者

如果你真的想疯了,你可以采取的get()assign()功能优势。 get()按字符调用对象,并且assign()可以创建一个。

mats <- c('cam','ped') 
mats.new <- NULL # initialize a matrix placeholder 
for (i in 1:length(mats)) { 
    mats.new <- get(mats[i]) # save as a new matrix each loop 
    # use dimnames with a list input to do both the row and column at once 
    dimnames(mats.new) <- list(LETTERS[1:dim(mats.new)[1]], 
          LETTERS[1:dim(mats.new)[2]]) 
    assign(mats[i],mats.new) # create (re-write) the matrix 
} 
+0

为什么你甚至要解释assign/get?没有人应该使用,但特别不是新手。 – Roland

1

如果数据集放在list我们可以使用lapply

lst <- lapply(mget(mats), function(x) { 
     dimnames(x) <- list(LETTERS[seq_len(nrow(x))], LETTERS[seq_len(ncol(x))]) 
    x}) 

这是更好地保持在一个list。如果原始对象需要更改

list2env(lst, envir = .GlobalEnv)