[R] merge dataframes
David Carlson
dcarlson at tamu.edu
Wed Jul 3 16:18:07 CEST 2013
In addition to reading Frequently Asked Questions Section 7.31, you
should always run your own code before posting. Yours does not work.
Spend some time reading one or more of the R tutorials and learn
about vectorization. It will save you time and typing. There are
many to choose from at
http://cran.r-project.org/other-docs.html
Do not try to match decimal values. Instead create an index value
that is a character string. Then you can match the character
strings:
> dat1<-data.frame(x=c(1.0,1.2,3.2,4.0,5.1),y=c(23,17,12,27,8))
> dat2 <- data.frame(x=seq(0.1,6,by=0.1),y=rep(0,60)) # Errors in
your code corrected here
> dat1$xc <- sprintf("%1.1f", dat1$x, 1) # Create dat1 index value
as character
> dat2$xc <- sprintf("%1.1f", dat2$x, 1) # Create dat2 index value
as character
> dat2[match(dat1$xc, dat2$xc),] <- dat1 # update dat2 with dat1
> dat2[dat2$y>0,] # Check the results
x y xc
10 1.0 23 1.0
12 1.2 17 1.2
32 3.2 12 3.2
40 4.0 27 4.0
51 5.1 8 5.1
> dat1
x y xc
1 1.0 23 1.0
2 1.2 17 1.2
3 3.2 12 3.2
4 4.0 27 4.0
5 5.1 8 5.1
-------------------------------------
David L Carlson
Associate Professor of Anthropology
Texas A&M University
College Station, TX 77840-4352
-----Original Message-----
From: r-help-bounces at r-project.org
[mailto:r-help-bounces at r-project.org] On Behalf Of jim holtman
Sent: Wednesday, July 3, 2013 7:22 AM
To: André de Boer
Cc: R mailing list
Subject: Re: [R] merge dataframes
FAQ 7.31
On Wed, Jul 3, 2013 at 7:55 AM, Andri de Boer <rnieuws at gmail.com>
wrote:
> Hello,
>
> I have two dataframes:
> dat1<-data.frame(x=c(1.0,1.2,3.2,4.0,5.1),y=c(23,17,12,27,8))
> dat2<-data.frame(x=seq(0,6,by=0.1),y=rep(0,60)))
>
> I want to replace the corresponding rows of dat2 with the ones of
dat1.
> I tried:
>
> for(i in 1:nrow(dat1))
> {
> dat2[dat2$x==dat1[i,1],2]<-dat1[i,2]
> }
>
> But I discovered that not every 5.1 is equal:
>
> > dat2[52,1][1] 5.1> dat1[5,1][1] 5.1> dat2[52,1]==dat1[5,1][1]
FALSE
>
>
>
> How to solve this?
>
>
>
> Regards,
>
> Andri
>
> [[alternative HTML version deleted]]
>
>
> ______________________________________________
> 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
Data Munger Guru
What is the problem that you are trying to solve?
Tell me what you want to do, not how you want to do it.
[[alternative HTML version deleted]]
More information about the R-help
mailing list