ベクトル V.Size の最大要素を取得し、N x N+1 の行列に出力する関数を作成しています。私の問題は、 V.Size が より小さい場合N*(N+1)
です。これが発生すると、行列は、s を出力したいときに、ベクトルの先頭に移動することから始めますNA
。
例えば:
# vector V.size is
V.size <- c(1,2,3,4,5,6)
# and N is
N <- 2
# then, the output matrix should be
c1 c2 c3
r1 6 5 4
r2 3 2 1
そして、がなくなるまでそれを埋めてから、最初からやり直すのではなく s を返しN*(N+1) > V.Size
たいです。V.Size
V.Size
NA
この問題を解決するための私の試みは、要素が以前のものよりも大きい場合を検索し、それをNA
. 私の試みた解決策はエラーを返します:
Error in if (is.na(m)[(i - 1), (y + 1)]) { : argument is of length zero
これが私のコードです:
# Function Name: one
# Input: V.Size (a vector) and N
# Output: Matrix size N by N+1
# Code:
one <- function(x,y) {
# sort the data, largest to smallest with N.A. last
temp <- sort(x, decreasing = TRUE, na.last = TRUE)
#creating the matrix
m <- matrix(head(temp, (y*(y+1))), # only takes elements that fit in the matrix
nrow = y, # number of rows = N
ncol = (y+1), # number of columns = N+1
byrow = TRUE) # filling it by row as instructed
if (length(x) < (y*(y+1))) { # if V.Size is smaller than the outputted matrix
for (i in seq_len(y)) { # for loop for columns
for (j in seq_len(y+1)) { # for loop for rows
if (m[i, j] > m[i,1]) { # if the element is larger than the first in the row
m[i, j] = NA # return NA
}
# HERE IS WHERE THINGS FAIL:
if (is.na(m)[(i-1), (y+1)]) { # if the last element in the previous row is NA
m[i, ] = NA # make current row NA
}
}
}
}
# print the output
m
}
# creating dummy data
V.Size <- c(1:10)
# choosing a dummy N
N = 5
one(V.Size, N)
エラーが発生します:Error in if (is.na(m)[(i - 1), (y + 1)]) { : argument is of length zero