[R] Create New variable

Peter Dalgaard p.dalgaard at biostat.ku.dk
Sun Sep 11 15:25:02 CEST 2005


Marc Bernard <bernarduse1 at yahoo.fr> writes:

> Dear All,
>  
> I want to create one numeric variable from a factor one. here is a simple example:
>  
> x1      x2     factor
> x11    x21    f1
> x12    x22    f1
> x13    x23    f2
> x14    x24    f3
> .        .         .
> .        .         .
>  
> Suppose that the variable factor has 3 levels (f1,f2,f3). I want to
> add to this data frame a numeric variable x4 in (v1,v2,v3) such that
> x4=v1 if factor = f1, x4 = v2 if factor = f2 and x4 = v3 if factor =
> f3.

Just use the factor as an index:

   x4 <- c(v1, v2, v3)[factor]

-- 

   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907




More information about the R-help mailing list