[R] Merge usage to update data.frame

jim holtman jholtman at gmail.com
Mon Jun 7 00:09:41 CEST 2010


try this:

> a
   V1 V2
1 AAA  1
2 BBB  2
3 CCC  3
> u
   V1 V2
1 BBB 22
> a$V2[match(u$V1, a$V1)] <- u$V2
> a
   V1 V2
1 AAA  1
2 BBB 22
3 CCC  3
>


On Sun, Jun 6, 2010 at 12:41 PM, Mario Valle <mvalle at cscs.ch> wrote:
> Good morning!
> I have two datasets with the same structure, one containing all my values
> and the second one that update same of these values (see example below).
> I want to create a data.frame with all the values of the first dataset
> except when an entry is present in the second dataset, in which case the
> second dataset value is taken.
>
> Is there a better method than my last line kludge?
> Thanks for your help!
>                        mario
>
>
> t1 <- textConnection("AAA 1
> BBB 2
> CCC 3")
> a <- read.table(t1, stringsAsFactors=FALSE)
> close(t1)
> t2 <- textConnection("BBB 22")
> u <- read.table(t2, stringsAsFactors=FALSE)
> close(t2)
> m <- merge(a, u, by="V1", all.x=TRUE)
> out <- data.frame(V1=m$V1, V2=ifelse(is.na(m$V2.y), m$V2.x, m$V2.y))
>
>
> --
> Ing. Mario Valle
> Data Analysis and Visualization Group            |
> http://www.cscs.ch/~mvalle
> Swiss National Supercomputing Centre (CSCS)      | Tel:  +41 (91) 610.82.60
> v. Cantonale Galleria 2, 6928 Manno, Switzerland | Fax:  +41 (91) 610.82.82
>
> ______________________________________________
> R-help at 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.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?



More information about the R-help mailing list