To my earlier question about updating a dataframe, and certainty that this 
has been solved several times before, Dr. Winsemius suggests  (Thanks!):
> I am sure this is not the most elegant method, but it will "work".
> 
> new <- merge(nn,uu, by = c("a","b"), all.x=T)
> new$y <- with( new, (ifelse(!is.na(x.y), y.y, y.x) )  )
> new$x <- with( new, (ifelse(!is.na(x.y), x.y, x.x) ) )
> new[ , c("a", "b", "x", "y")]
>     a b           x             y
> 1  1 1 100.0000000 -100.00000000
> 2  1 2   0.7682636    0.28821953
> 3  1 3   0.6274436    0.08373154
> 4  2 1   0.2750319    0.55738251
> 5  2 2 200.0000000 -100.00000000
> 6  2 3   0.1919333    0.88803516
> 7  3 1   0.3606559    0.72215405
> 8  3 2   0.9396269    0.10943878
> 9  3 3 300.0000000 -100.00000000
> 10 4 1 400.0000000 -100.00000000
> 11 4 2   0.5633217    0.63063714
> 12 4 3   0.3712922    0.40779830

That was one of the methods I've considered, but the with() function 
cleans it up considerably.  I'll have to get more familiar with that.

I've also tried a merge()-less update that seems to work.  Still not quite 
as transparent as an SQL UPDATE or SAS MERGE step.  Can anyone suggest an 
improvement or alternate to either method?

nn <- expand.grid('a'=1:4, 'b'=1:3)
nn$x <- runif(nrow(nn))
nn$y <- runif(nrow(nn))
uu <- rbind(data.frame('a'=1, 'b'=1, 'x'=100, 'y'=-100)
           ,data.frame('a'=2, 'b'=2, 'x'=200, 'y'=-100)
           ,data.frame('a'=4, 'b'=1, 'x'=400, 'y'=-100)
           ,data.frame('a'=3, 'b'=3, 'x'=300, 'y'=-100)
           )

# This works, but it's sensitive to the order of the updates in uu.
corr <- nn
corr[paste(corr$a, corr$b) %in% paste(uu$a, uu$b),]$x <- uu$x
corr[paste(corr$a, corr$b) %in% paste(uu$a, uu$b),]$y <- uu$y

# try updates in a different order, and it puts the updates in the wrong 
rows
uu<-uu[c(2,4,3,1),] 
corr <- nn
corr[paste(corr$a, corr$b) %in% paste(uu$a, uu$b),]$x <- uu$x
corr[paste(corr$a, corr$b) %in% paste(uu$a, uu$b),]$y <- uu$y

# ordering the dataframes first seems to work well.
ord.uu <- uu[order(uu$a, uu$b),]
corr <- nn[order(nn$a, nn$b),]
corr[paste(corr$a, corr$b) %in% paste(ord.uu$a, ord.uu$b),]$x <- ord.uu$x
corr[paste(corr$a, corr$b) %in% paste(ord.uu$a, ord.uu$b),]$y <- ord.uu$y


Enjoy the days,
cur
-- 
Curt Seeliger, Data Ranger
Raytheon Information Services - Contractor to ORD
seeliger.c...@epa.gov
541/754-4638

        [[alternative HTML version deleted]]

______________________________________________
R-help@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.

Reply via email to