[R] merge dataframes with conditions formulated as logical expressions
Wolfram Fischer
wolfram at fischer-zim.ch
Wed Jun 14 16:55:07 CEST 2006
I have a data.frame df containing two variables:
GRP: Factor
VAL: num
I have a data.frame dp containing:
GRP: Factor
MIN.VAL: num
MAX.VAL: num
VAL2: num
with several rows per "GRP"
where dp[i-1, "MAX.VAL"] < dp[i, "MIN.VAL"]
within the same "GRP".
I want to create df[i, "VAL2"] <- dpp[z, "VAL2"]
with i along df
and dpp <- subset( dp, GRP = df[i, "GRP"] )
so that it is true for each i:
df[i, "VAL"] > dpp[z, "MIN.VAL"]
and df[i, "VAL"] <= dpp[z, "MAX.VAL"]
Is there an easy/efficient way to do that?
Example:
df <- data.frame( GRP=c( "A", "A", "B" ), VAL=c( 10, 100, 200 ) )
dp <- data.frame( GRP=c( "A", "A", "B", "B" ),
MIN.VAL=c( 1, 50, 1, 70 ), MAX.VAL=c( 49, 999, 59, 999 ),
VAL2=c( 1.1, 2.2, 3.3, 4.4 ) )
The result should be:
df$VAL2 <- c( 1.1, 2.2, 4.4 )
Thanks - Wolfram
More information about the R-help
mailing list