From: Uwe Ligges <ligges at statistik.uni-dortmund.de>
To: peter leonard <pfleonard at hotmail.com>
CC: r-help at stat.math.ethz.ch
Subject: Re: [R] function to populate a matrix based on a lookup to another
matrix ?
Date: Sat, 31 May 2003 17:58:27 +0200
peter leonard wrote:
Hi,
This is a beginner R question.
I have a 4x4 matrix named 'lookup' with the following values:
1 2 3 4
1 0.000000 2.828427 5.656854 8.485281
2 2.828427 0.000000 2.828427 5.656854
3 5.656854 2.828427 0.000000 2.828427
4 8.485281 5.656854 2.828427 0.000000
I then create a new empty matrix named 'dd' with specfic row and col names
:
1 3 4 3 3 1
1 NA NA NA NA NA NA
2 NA NA NA NA NA NA
3 NA NA NA NA NA NA
4 NA NA NA NA NA NA
3 NA NA NA NA NA NA
2 NA NA NA NA NA NA
1 NA NA NA NA NA NA
I want to be able populate the cells in 'dd' using 'lookup' based on the
specified rownames and colnames of 'dd'. For example, the cell in 'dd'
where the rowname =2 and the colname = 1 should be assigned the value
2.828427 .
I've tried several ways of doing this with the apply function but without
success. I can do it with a for loop but I want to avoid that for
efficiency reasons.
After running the function, as an example, the first column of 'dd' should
look like this :
1
1 0.000000000
2 2.828427125
3 5.656854249
4 8.485281374
3 5.656854249
2 2.828427125
1 0.000000000
Can anyone please help me identify the required function or an alternative
way of achieving the same result? Hopefully this is simple and I'm just
not seeing it.
Thanks
Peter
dd <- lookup[as.numeric(rownames(dd)), as.numeric(colnames(dd))]
and after that restoring dd's row- and colnames.
Anyway, I guess you don't need to create "dd". Just calculate those
rownames (rn) and colnames (cn) as integers. Then the following works:
dd <- lookup[rn, cn]
Uwe Ligges