[R] Matrix from a vector?

Sundar Dorai-Raj sundar.dorai-raj at pdf.com
Thu Sep 21 21:53:52 CEST 2006

kone said the following on 9/21/2006 2:30 PM:
> Hi,
>
> Is there some function, which generates this kind of n x n -matrix
> from a vector?
>
>  > rhset
> [1]  1792   256 13312   512  1024  2048  8192  4096
>  > 	m=matrix(nrow=length(rhset),ncol=length(rhset))
>  > 	for(i in 1:length(rhset))
> + 	{
> + 		m[,i]=rhset
> + 		rhset=c(rhset[length(rhset)], rhset[2:length(rhset)-1])
> + 	}
>  > m
>        [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]
> [1,]  1792  4096  8192  2048  1024   512 13312   256
> [2,]   256  1792  4096  8192  2048  1024   512 13312
> [3,] 13312   256  1792  4096  8192  2048  1024   512
> [4,]   512 13312   256  1792  4096  8192  2048  1024
> [5,]  1024   512 13312   256  1792  4096  8192  2048
> [6,]  2048  1024   512 13312   256  1792  4096  8192
> [7,]  8192  2048  1024   512 13312   256  1792  4096
> [8,]  4096  8192  2048  1024   512 13312   256  1792
>
>
> Atte Tenkanen
> University of Turku, Finland
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

Does this work for you?

rhsel <- c(1792, 256, 13312, 512, 1024, 2048, 8192, 4096)
n <- length(rhsel)
i <- sapply(1:n, function(i) (1:n - i)%%n + 1)
matrix(rhsel[i], n, n)

HTH,

--sundar