[R] how to extract specific subscript of a matrix

Rasmus Liland jr@| @end|ng |rom po@teo@no
Thu Jun 11 03:21:40 CEST 2020


On 2020-06-10 18:01 -0700, Jeff Newmiller wrote:
> On June 10, 2020 5:29:10 PM PDT, Jinsong Zhao wrote:
> > 
> > (3,1), (5,1), (5,2), (4,2), (4,3), (1,3), (1,2), (3,2)
> 
> M <- matrix(c(2,2,rep(1,12), 2), nrow = 5,byrow = FALSE)
> ix <- expand.grid( r = seq.int( nrow( M ) )
>                  , c = seq.int( ncol( M ) )
>                  )
> ix[ 1 == c(M), ]

Dear Jinsong and Jeff,

I thought out this, really similar to Jeff's answer:

	M <- matrix(c(2, 2, rep(1, 12), 2),
	            nrow=5, byrow=FALSE)
	
	points <- expand.grid(1:nrow(M), 1:ncol(M))
	points <- apply(points, 1, paste, collapse=",")
	points <- matrix(paste0("(", points, ")"),
	                 nrow=nrow(M))
	
	paste(points[M==1], collapse=", ")

you get

	[1] "(3,1), (4,1), (5,1), (1,2), (2,2), (3,2), (4,2), (5,2), (1,3), (2,3), (3,3), (4,3)"

Best,
Rasmus

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20200611/5675bb5e/attachment.sig>


More information about the R-help mailing list