[R] Replacing variables in one dataset with those from another

Dennis Murphy djmuser at gmail.com
Thu Jun 2 00:27:40 CEST 2011


Hi:

Letting d1 and d2 be your two data frames,

> merge(d1, d2, by.x = 'x1', by.y = 'num', all.x = TRUE)[, c(2, 4, 3)]
  grpnum       uniqueid   x2
1      D           <NA>  276
2      B           <NA>  898
3      A GHU82RK02HD7D6  334
4      C GHU82RK02IXPC7 4077

If you want x1 to be the variable name for the new dataset, then

dmerge <- merge(d1, d2, by.x = 'x1', by.y = 'num', all.x = TRUE)[, c(2, 4, 3)]
names(dmerge)[2] <- 'x1'

HTH,
Dennis

On Wed, Jun 1, 2011 at 11:30 AM, mcginnis21 <mcginnis at montana.edu> wrote:
> Hoping someone out there can help me...this seems like an easy task but I
> can't figure it out...
>
> I want to replace variables in one dataset (Dataset1) with a variable from
> another dataset (Dataset2).
> All the values for variables x1 and x2 in Dataset1 have a unique match to
> the variable uniquenum in Dataset2.  For example, in Dataset1 grpnum A has a
> value of 343 for variable x1.  In Dataset2, 343 will only be found once for
> variable uniquenum.  I would like to create a new dataset where the variable
> x1 from Dataset1 will be replaced by uniqueid from Dataset2.  So variable x1
> for grpnum A now would equal GHU82RK02HD7D6 rather than 343.   Below is an
> abbreviated example from my datasets to show what I’m trying to do rather
> than explain in words because I’m not sure my question is coming across very
> clearly.   I have about 100 columns in Dataset1 (x1, x2, etc.) and the
> variable uniquenum in Dataset2 has about 4,000 values.
>
> Dataset1
> grpnum  x1      x2
> A       343     334
> B       313     898
> C       4076    4077
> D       275     276
>
> Dataset2
> unique num      uniqueid
> 343     GHU82RK02HD7D6
> 4076    GHU82RK02IXPC7
> 4077    GHU82RK02HICZ2
> 261     GHU82RK02FLOFU
> 4100    GHU82RK02IDO7K
> 4101    GHU82RK02HQYQL
> 4102    GHU82RK02GADV1
> 4103    GHU82RK02G7RQH
> 4104    GHU82RK02HQD2E
>
>
>
> NewDataset
> grpnum  x1      x2
> a       GHU82RK02HD7D6    Na
> b       Na      Na
> c       GHU82RK02IXPC7  GHU82RK02HICZ2
> d       Na      Na
>
>
>
> Thanks for your time and thoughts.  I hope someone can help!
>
>
>
> --
> View this message in context: http://r.789695.n4.nabble.com/Replacing-variables-in-one-dataset-with-those-from-another-tp3566552p3566552.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list