[R] Efficient way to use data frame of indices to initialize matrix

Whit Armstrong armstrong.whit at gmail.com
Tue Dec 7 19:40:58 CET 2010


index m as a vector and do the assignment in one step

i <- df$row + (df$col-1)*nrow(m)
m[i] <- df$a

or something along those lines.

-Whit


On Tue, Dec 7, 2010 at 1:31 PM, Cutler, Gene <gcutler at amgen.com> wrote:
> I have a data frame with three columns, x, y, and a.  I want to create a matrix from these values such that for matrix m:
> m[x,y] == a
>
> Obviously, I can go row by row through the data frame and insert the value a at the correct x,y location in the matrix.  I can make that slightly more efficient (perhaps), by doing something like this:
>> for (each.x in unique(df$x)) m[each.x, df$y[df$x == each.x]] <- df$a[df$x == each.x]
>
> But I feel that there must be a more efficient, or at least more elegant way to do this.
>
> --
> Gene
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list