[R] SAS-like method of recoding variables?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Jun 22 20:56:12 CEST 2009


Mark Na wrote:
> Dear R-helpers,
> 
> I am helping a SAS user run some analyses in R that she cannot do in
> SAS and she is complaining about R's peculiar (to her!) way of
> recoding variables. In particular, she is wondering if there is an R
> package that allows this kind of SAS recoding:
> 
> IF TYPE='TRUCK' and count=12 THEN VEHICLES=TRUCK+((CAR+BIKE)/2.2);

vehicles <- ifelse(TYPE=='TRUCK' & count=12, TRUCK+((CAR+BIKE)/2.2), NA)

or maybe

newdata <- within(mydata,
    vehicles <- ifelse(TYPE=='TRUCK' & count=12,
         TRUCK+((CAR+BIKE)/2.2), NA)
)

or transform(mydata, vehicles=....)

or, if you insist on only having the calculation done for the subgroup,

sub <- with(mydata, TYPE=='TRUCK' & count=12)
sub <- sub && !is.na(sub)
mydata$vehicles <- NA
mydata$vehicles[sub] <- with(mydata[sub,],  TRUCK+((CAR+BIKE)/2.2) )

(all assuming that there's no "vehicles" in the data to begin with).


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