Steve's method is very slick.
I think this is a bit easier to understand.
A <- matrix(1:9, 3, 3)
A
B <- matrix(nrow=2, ncol=3)
B[lower.tri(B, diag=TRUE)] <- A[lower.tri(A)]
B[upper.tri(B, diag=FALSE)] <- A[upper.tri(A)]
B
> A <- matrix(1:9, 3, 3)
> A
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9
> B <- matrix(nrow=2, ncol=3)
> B[lower.tri(B, diag=TRUE)] <- A[lower.tri(A)]
> B[upper.tri(B, diag=FALSE)] <- A[upper.tri(A)]
> B
[,1] [,2] [,3]
[1,] 2 4 7
[2,] 3 6 8
>
On Wed, Nov 14, 2018 at 11:04 AM S Ellison <[email protected]> wrote:
>
> i) Your code creates w2 but references w1 to create aa.
>
> So you needed
> aa <- matrix(rep(c(0.4, 0.1, 0.2), 3), 3,3)
> for a working example.
>
> ii) This
> > matrix(as.numeric(aa)[!as.numeric(aa) %in% diag(aa)],2,3)
> removes any value that is present in the diagonal of aa. Look up ?"%in%" to
> see what that does; it returns TRUE whenever anything in as.numeric(aa)
> matches anything in your diagonal. All the values in aa match one of c(0.4,
> 0.1, 0.2). So since your whole matrix consists of these three numbers, you
> told R to leave out everything in aa and then create a 2x3 matrix with the
> result. Hence the NAs
>
> iii) If you want to extract odd parts of a matrix explicitly, see ?"[" and
> particularly the section on indexing using arrays
>
> iv) You can use logical indexing. In the special case of the diagonal, you
> can use diag() to create a matrix of logicals, logically negate that and
> apply that to your matrix:
> aa[ !diag(rep(TRUE, 3)) ]
>
> and, in twoi rows:
> matrix( aa[ !diag(rep(TRUE, 3)) ], 2,3)
>
> > for examplei have this matrix
> > w2<-c(0.1,0.2,0.4,0.2,0.4,0.1)
> > aa<-matrix(w1,nrow=3,ncol=3)
> > aa
> > [,1] [,2] [,3]
> > [1,] 0.4 0.4 0.4
> > [2,] 0.1 0.1 0.1
> > [3,] 0.2 0.2 0.2
> >
> > if i use this code
> > matrix(as.numeric(aa)[!as.numeric(aa) %in% diag(aa)],2,3)
> >
> > i will obtaine this matrix[,1] [,2] [,3]
> > [1,] NA NA NA
> > [2,] NA NA NA
> >
> > but me i want this matrix[,1] [,2] [,3]
> > [1,] 0.1 0.4 0.4
> > [2,] 0.2 0.2 0.1
> >
> > thank you
> >
> > [[alternative HTML version deleted]]
> >
> > ______________________________________________
> > [email protected] mailing list -- To UNSUBSCRIBE and more, see
> > https://stat.ethz.ch/mailman/listinfo/r-help
> > PLEASE do read the posting guide http://www.R-project.org/posting-
> > guide.html
> > and provide commented, minimal, self-contained, reproducible code.
>
>
> *******************************************************************
> This email and any attachments are confidential. Any u...{{dropped:14}}
______________________________________________
[email protected] mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.