0

我正在编写一个函数,该函数将向量 V.Size 中的最大元素输出到 N 乘以 N+1 的矩阵中。我的问题是当 V.Size 小于N*(N+1). 发生这种情况时,矩阵首先到达向量的顶部,而我希望它输出NAs。

例如:

# 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用完然后返回NAs 而不是重新开始。

我解决这个问题的尝试是通过搜索元素何时大于前一个元素并将其替换为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

4

2 回答 2

1

这个怎么样?

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
于 2013-06-17T07:17:53.093 回答
0

我认为问题出在循环的第一次运行中。当循环第一次运行时,您不应该检查条件。即当i-1 = -1 或 i=1时不检查。第一次跑步应该没有以前的会员!!!

于 2013-06-17T06:57:33.213 回答