[R] Help with matrix

jim holtman jholtman at gmail.com
Sat Jul 26 05:39:43 CEST 2008


Is this what you want:

> x <- read.table(textConnection("g1  g2  f
+ 3   4  10
+ 2   1  30
+ 4   4  50"), header=TRUE)
> closeAllConnections()
> # create empty matrix
> mat <- matrix(0, max(x$g1), max(x$g2))
> mat[cbind(x[,1], x[,2])] <- x[,3]
> mat
     [,1] [,2] [,3] [,4]
[1,]    0    0    0    0
[2,]   30    0    0    0
[3,]    0    0    0   10
[4,]    0    0    0   50
>
>


On Fri, Jul 25, 2008 at 11:30 PM, Van Wyk, Jaap <jaapvw at uj.ac.za> wrote:
> Hi
> I have 3 vectors, say g1, g2 and f, where g1 and g2 contain the row and column indices of a matrix, with corresponding elements in f. How can I create a matrix containing the values in f ?
> For example:
> g1  g2  f
> 3   4  10
> 2   1  30
> 4   4  50
> How can then get a matrix that looks as follows:
>  0   0   0   0
> 30  0   0   0
>  0   0   0   10
>  0   0   0   50
>
> I am still learning R. I think reshape will help, but it is not clear how that works here.
>
> Any help is much appreciated.
> Thank you.
> Jacob
>
>
> Jacob L van Wyk
> Department of Statistics
> University of Johannesburg, APK
> Box 524
> Auckland Park 2006
> South Africa
> Office Tel: +27 11 559 3080
> Fax: +27 11 559 2832
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem you are trying to solve?



More information about the R-help mailing list