[R] Replacing data.frame values

Thomas Lumley tlumley at u.washington.edu
Sat Jan 19 00:01:00 CET 2002


On Fri, 18 Jan 2002, Dennis L. Malandro wrote:

> Hello,
>
> I have two data frames, NameAndConc.df and
> WhichOnes.df.  NameAndConc.df has two columns, the
> first column is the names of some material, and the
> second column is the concentration of active
> ingredient.
>
> > NameAndConc.df
>        name conc
> 1 material1  0.8
> 2 material2  0.5
> 3 material3  0.4
>
> WhichOnes.df has two columns, each of which specifies
> which material.
>
> > WhichOnes.df
>   component1 component2
> 1  material2  material3
> 2         NA  material1
> 3  material3  material2
> 4  material2         NA
>
> From these two data.frames, I'd like to generate a
> third data frame that is WhichOnes.df with the names
> replaced by the corresponding concentrations from
> NameAndConc.df.  So it would be
>
> > New.df
>   component1 component2
> 1        0.5        0.4
> 2         NA        0.8
> 3        0.4        0.5
> 4        0.5         NA
>
>
> Would someone please lend me a help'n hand with this?

You need match().
  match(New.df$component1,Nameandconc.df$name)
gives the row numbers in Nameandconc.df corresponding to the names of
component 1.

So
 Nameandconc.df$conc[match(New.df$component1,Nameandconc.df$name)]
gives the concentrations

and to do them all at once

apply(New.df, 2, function(this.component)
       Nameandconc.df$conc[match(this.component, Nameandconc.df$name)])


	-thomas

Thomas Lumley			Asst. Professor, Biostatistics
tlumley at u.washington.edu	University of Washington, Seattle

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list