[R] Indexing to insert values from a dataframe into a matrix

Sarah Goslee sarah.goslee at gmail.com
Wed Jun 29 12:15:37 CEST 2011


Hi Daisy,

You've got a conceptual problem and a couple of practical ones, I think.

On Tue, Jun 28, 2011 at 9:29 PM, Daisy Englert Duursma
<daisy.duursma at gmail.com> wrote:
> Hello,
>
> I think this is a simple problem but I am not coming up with a simple
> solution. I think it just an indexing problem.
>
> I can easily replace values in a matrix from a dataframe when the
> dataframe has row and column numbers. In the example below I use row
> and column names and  I can not get it to work

It's not so much that a matrix has row and column numbers instead of
names, as that any matrix or dataframe can be indexed numerically.

> #make a matrix where rows and columns are the lat and long for a
> bounding box of Australia and all elements have the value of -9990
>
> bb<-matrix(c(rep(-9999,691*886)),nrow=691
> ,ncol=886,dimnames=list(seq(-10,-44.50,by=-0.05),seq(112,156.25,by=0.05)))
>
> #dfr with row names and col names and values to be replaced in the matrix
>
> dfr <- data.frame(cbind(x=seq(120,125,by=0.05), y=-25, var.1=1))

Why are you making this into a dataframe? You're ending up with y
containing -25 repeated 101 times, and var.1 containing 1 repeated 101
times. If these aren't actually going to be different in your final
version, I'd make a list instead.

Also, x actually corresponds to the column names of bb, and y to the rownames.

> #insert the values from the dfr into the matrix
> bb[dfr$x,dfr$y]<-d$var.1

And then you're trying to use x and y for indexing, rather than
comparing them to the names of bb.

You need to use (with x and y switched):
bb[rownames(bb) %in% as.character(dfr$y), colnames(bb) %in% as.character(dfr$x)]

And you can assign anything you want to that, except d$var.1 because
that doesn't exist. Presumably you mean dfr$var.1.


Sarah

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list