2017-05-28 9 views
0

今日はRを使い始めましたので、あまりにも基本的であれば謝ります。ベクトル要素のループ、要素が行列

まず、2つの行列を構成し、その行列のエントリを持つベクトルを構築します。次に、ベクトルの要素、すなわち行列をループしようとします。しかし、私がすると、私は "長さゼロの引数"エラーを取得します。

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

質問:どのようにベクトルの要素をループに、これらの要素があることの行列を次のように

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]] 
} 

エラーテキストはありますか? (私は要素を正しく呼んでいないと思います)。忍耐力ありがとうございます。

答えて

2

がgo-にRでのオプションは、リストを使用することです:あなたは本当にクレイジー取得したい場合は、get()assign()機能を利用することができます

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()はオブジェクトを作成できます。

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) 
関連する問題