【发布时间】:2017-03-20 00:32:24
【问题描述】:
以 DV 和 FF 作为长度为 47 的向量:
analyse <- function(DV,FF)
{
correct <- rep(0,47)
matrix <- array(rep(0,47*3), dim=c(47,3))
for(i in 1:47)
{
if(DV[i] > 50) {if(FF[i] > 50) {correct[i] <- i}
}
else
{
if(FF[i] < 0){correct[i] <- i}}
}
for(i in 1:47)
{
if((correct[i] == 0) == FALSE)
{
matrix[i,1] <- DV[i]
matrix[i,2] <- FF[i]
matrix[i,3] <- matrix[i,1] - matrix[i,2]
}
}
for(i in 47:1)
{
if(matrix[i,1]==0) {matrix<-matrix[-i]
}
}
return(matrix)
}
我不明白为什么会出现此错误:
矩阵[i, 1] 中的错误:维数不正确
提前致谢
[编辑]样本数据:
DV <- c(56.2, 59.2, 50.9, 46.9, 50.7, 47.3, 53.6, 57.8, 42.7, 45.0, 47.3, 44.1, 51.5, 50.0, 50.3, 50.4, 51.7, 47.8, 46.8, 40.0, 45.5, 57.4, 51.6, 36.1, 34.8, 41.2, 59.1, 62.5, 55.0, 53.8, 52.4, 44.5, 42.2, 50.1, 61.3, 49.6, 38.2, 51.1, 44.7, 40.8, 46.1, 53.5, 54.7, 50.3, 48.8, 53.7, 52.0)
DF <- c(49.95662, 51.93295, 53.02263, 50.00784, 48.55493, 49.93520, 48.70022, 50.98856, 52.51411, 47.02938, 47.86480, 48.70022, 47.53790, 50.22578, 49.68094, 49.78991, 49.82623, 50.29842, 48.88184, 48.51861, 46.04866, 48.04641, 52.36882, 50.26210, 44.63208, 44.15988, 46.48454, 52.98631, 54.22128, 51.49707, 51.06120, 50.55268, 47.68319, 46.84776, 49.71726, 53.78541, 49.53565, 45.39485, 50.08049, 47.75583, 46.33925, 48.26435, 50.95223, 51.38811, 49.78991, 49.24506, 51.02488)
[edit] result:
Scope of the function it to obtain a matrix which contains:
- every couple of DV[i] and FF[i] which are not both higher (or lower) than 50.
- their difference as third column.
example:
DV[1] = 55
FF[1] = 45
DV > 50 and FF < 50, so I report them in the matrix:
DV[1] -> matrix [1,1]
FF[1] -> matrix[1,2]
第三列是他们的区别:
matrix[1,3] <- matrix[1,1] - matrix[1,2].
当 DV[2] = 55 和 FF[2] = 55 时,analyze() 什么都不做,因为它们都高于 50。
【问题讨论】:
-
如果你做
matrix <- matrix[-i]这样的事情,你会期待什么? -
不管用吗?你能纠正我吗?
-
您的示例不完整。您尚未定义
DV或FF是什么作为输入。几乎可以肯定循环是不必要的。空格有助于使您的代码更具可读性。 -
它们都是长度为 47 的两个向量。我不需要使它成为必要的,只是一个工作代码。
-
代码没有正确缩进。这是不可读的。运算符周围没有空格,尤其是
<-。请编辑。
标签: arrays r function matrix dimensions