[R] Selecting rows conditionally between 2 data.frames

jiho jo.irisson at gmail.com
Fri Jan 18 17:36:59 CET 2008


Hello everyone,

I have two data.frames that look like

calib:
place	zoom	scale
left		0.65		8
left		0.80		5.6
left		1.20		3
right		0.65		8.4
right		0.80		6
right		1.20		2.9

X:
...	place	zoom	....
...	left		0.80		....
...	left		1.20		....
...	right		0.65		....
...	NA		NA		....
...	right		0.8		....
...	left		1.20		....

and I want to get the corresponding values of 'scale' in a new column  
in X, i.e.:
X:
...	place	zoom	....	scale
...	left		0.80		....	5.6
...	left		1.20		....	3
...	right		0.65		....	8.4
...	NA		NA		....	NA
...	right		0.8		....	6
...	left		1.20		....	3

I tried various combination of `which` and `match` but could not make  
it work.
I fell back on defining a custom function and applying it over the lines
	get.scales <- function(x)
	{
		if (is.na(x$zoom)) {
			scaleF = NA
		} else {
			scaleF = calib[calib$zoom==x$zoom & calib$place==x$place, "scale"]
		}
		return(scaleF)
	}
and
	apply(X, 1, get.scales)
but:
- this is not very practical since using apply apparently converts the  
data to an array and looses column titles (i.e. x$size does not work,  
I need to use column numbers, which I'd rather not)
- I feel there is an easier, vector based way.

I would welcome suggestions. Thank you in advance.

JiHO
---
http://jo.irisson.free.fr/



More information about the R-help mailing list