[R] simple "for loop" program for merging datasets?
David Winsemius
dwinsemius at comcast.net
Thu Mar 19 23:32:18 CET 2009
You say you want to merge the two datasets on Country but the last
step in you unsuccessful effort tries to match the results of the
nested loop (necessarily with values of Measure2 from B) to B which
has 3 rows. You never told us what the final results of this effort
should be. but surely it is not matching Measure2 up with elements in B.
(Also notice that Country_A[j]= =(Country_B[i] could not possibly do
anything useful due to the space between the two equal signs.)
Try again to construct a sensible question, copy the results from your
efforts, and someone will take a stab at offering help.
I suggest you offer dput(A) and dput(B) so we can see whether the
colnames really have spaces in them.
--
David Winsemius
On Mar 19, 2009, at 5:35 PM, J S wrote:
>
> Dear R community,
>
> I would like to merge two datasets based on the categorical
> predictor country.
>
> Dataset A:
>
> Country Measure1
> Afganistan 1
> Afganistan 1
> Russia 5
> Poland 3
> Poland 2
>
> Dataset B:
>
> Country Measure 2
> Russia 2
> Afganistan 10
> Poland 15
>
> My program does not work:
>
> Country_A<-A$Country
> Country_B<-B$Country
> Measure2<-B$Measure2
>
> for(i in 1:nrow(B)){
> for(j in 1:nrow(A){
> w[j]<-ifelse(Country_A[j]= =(Country_B[i]),Measure2[i], NA)
> }}
>
> A2<-cbind(B,w)
>
>
> Thanks, Julia
>
> _________________________________________________________________
>
>
> [[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.
David Winsemius, MD
Heritage Laboratories
West Hartford, CT
More information about the R-help
mailing list