[R] How to define new matrix based on an elementary row operation in a single step?
Gabor Grothendieck
ggrothendieck at gmail.com
Sat Aug 28 13:27:30 CEST 2010
On Sat, Aug 28, 2010 at 1:32 AM, Cheng Peng <cpeng at usm.maine.edu> wrote:
>
> Sorry for possible misunderstanding:
>
> I want to define a matrix (B) based on an existing matrix (A) in a single
> step and keep A unchanged:
>
>> #Existing matrix
>> A=matrix(1:16,ncol=4)
>> A
> [,1] [,2] [,3] [,4]
> [1,] 1 5 9 13
> [2,] 2 6 10 14
> [3,] 3 7 11 15
> [4,] 4 8 12 16
>> # New matrix B is defined to be the submatrix after row1 and column1 are
>> deleted.
>> B=A[-1,-1] # this single step deletes row1 nad column 1 and assigns the
>> name to the resulting submatrix.
>> B # check the new matrix B
> [,1] [,2] [,3]
> [1,] 6 10 14
> [2,] 7 11 15
> [3,] 8 12 16
>> A # check the original matrix A
> [,1] [,2] [,3] [,4]
> [1,] 1 5 9 13
> [2,] 2 6 10 14
> [3,] 3 7 11 15
> [4,] 4 8 12 16
>
>
> Question: How can I do define a new matrix (D) by adding 2*row1 to row3 in A
> in a single step as what was done in the above example?
>
> If you do: A[3,]=2*A[1,]+A[3,], the new A is not the original A; if you
> D=A first, then D[3,]=2*D[1,]+D[3,], you used two step!
>
> Hope this clarifies my original question. Thanks again.
>
Try using replace:
D <- replace(A, row(A) == 3, 2 * A[1,] + A[3,])
--
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com
More information about the R-help
mailing list