我正在编写一个函数,该函数将向量 V.Size 中的最大元素输出到 N 乘以 N+1 的矩阵中。我的问题是当 V.Size 小于N*(N+1)
. 发生这种情况时,矩阵首先到达向量的顶部,而我希望它输出NA
s。
例如:
# 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
而当N*(N+1) > V.Size
,我想V.Size
填充它直到V.Size
用完然后返回NA
s 而不是重新开始。
我解决这个问题的尝试是通过搜索元素何时大于前一个元素并将其替换为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