1

我想选择矩阵或向量的特定元素,可以说大于 0。一种选择是循环遍历矩阵/向量的每个元素,但我想知道是否有更好的方法来实现这一点(比如在 R 中,使用哪个条件)。我的代码如下所示:

matrix.
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}.
compute b=0.

loop #i=1 to ncol(A).
    do if ( A(1,#i) >0 ).
        compute b={b,a(1,#i)}.
    end if.
end loop.

compute b=b(1,2:ncol(b)).
print b.

end matrix.
4

1 回答 1

0

如果你有你想要的索引,你可以简单地在一个单独的子集向量中提供它们。

matrix.
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}.
compute take = {1,2,4}.
print A(take).
end matrix.

1 2 6在打印语句上产生。现在,抓取索引有点烦人。一种方法是使用GRADE满足条件的否定,它提供了一个顺序来获取你想要的索引。然后只选择您知道满足条件的索引总数。

matrix.
compute A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}.

*make sequential index and vector with selection.
compute take = {1:NCOL(A)}.
compute sel = A > 0.

*reording the indices so the selected columns are first.
compute take(GRADE(-1*sel)) = take.

*only taking the indices that meet the selection.
compute take = take(1:RSUM(sel)).

*results.
print A.
print A(take).
end matrix.

这可以汇总到一个宏中以使这更容易。这是一个可以在这里工作的例子。

DEFINE !SelCol (Data = !TOKENS(1)
               /Condition = !TOKENS(1) 
               /Result = !TOKENS(1) )
COMPUTE XKeepX = !UNQUOTE(!Condition).
COMPUTE XIndX = {1:NCOL(!Data)}.
COMPUTE XIndX(GRADE(XKeepX*-1)) = XIndX.
COMPUTE XIndX = XIndX(1:RSUM(XKeepX)).
COMPUTE !Result = !Data(1:NROW(!Data),XIndX).
RELEASE XKeepX.
RELEASE XIndX.
!ENDDEFINE.

MATRIX.
COMPUTE A={1,2,5,6,1,6,0,4,0,3,6,0,2,-3}.
!SelCol Data=A Condition='A>0' Result=ASel.
PRINT ASel.
END MATRIX.

这种方法也很容易适用于选择矩阵的特定行。

DEFINE !SelRow (Data = !TOKENS(1)
               /Condition = !TOKENS(1)
               /Result = !TOKENS(1) )
COMPUTE XKeepX = !UNQUOTE(!Condition).
COMPUTE XIndX = {1:NROW(!Data)}.
COMPUTE XIndX(GRADE(XKeepX*-1)) = XIndX.
COMPUTE XIndX = XIndX(1:CSUM(XKeepX)).
COMPUTE !Result = !Data(XIndX,1:NCOL(!Data)).
RELEASE XKeepX.
RELEASE XIndX.
!ENDDEFINE.

这应该很快。大部分时间将花在条件语句和提取数据上。即使对于大量的行或列,对索引进行排名也应该非常简单。

于 2014-07-16T20:57:04.600 回答