[R] Replacing data.frame values

Peter Dalgaard BSA p.dalgaard at biostat.ku.dk
Sat Jan 19 00:18:03 CET 2002


"Dennis L. Malandro" <nawlnz at yahoo.com> writes:

> 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?
> 

Let's see... First of all, the structure of NameAndConc.df is getting
in the way since the name field is a key, not really a variable, so
try a named vector instead:

conc <- NameAndConc.df$conc
names(conc) <- NameAndConc.df$name

Then use the columns of WhichOnes.df for indexing:

New.df <-
data.frame(component1=conc[as.character(WhichOnes.df$component1)],
           component2=conc[as.character(WhichOnes.df$component2)])

or, 

New.df <- lapply(WhichOnes.df, function(x)conc[as.character(x)])

..something like that. I suppose you could use match() instead of the
character indexing.



-- 
   O__  ---- Peter Dalgaard             Blegdamsvej 3  
  c/ /'_ --- Dept. of Biostatistics     2200 Cph. N   
 (*) \(*) -- University of Copenhagen   Denmark      Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)             FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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