我正在写一个函数,它将取向量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
这个怎么样?
V.size <- 1:6
N <- 3
matrix(sort(V.size, decreasing=TRUE)[1:(N*(N+1))], nrow=N, byrow=TRUE)
[,1] [,2] [,3] [,4]
[1,] 6 5 4 3
[2,] 2 1 NA NA
[3,] NA NA NA NA
我认为问题是在循环的第一次运行。当循环第一次运行时,不应该检查条件。即,当i-1 = -1或i=1时,则不检查。不会有以前的成员第一次运行!!