[R] Setting elements in data frame

Peter Dalgaard BSA p.dalgaard at pubhealth.ku.dk
Thu Feb 22 15:29:47 CET 2001


Kaspar Pflugshaupt <pflugshaupt at cirsium.ethz.ch> writes:

> On Thursday 22 February 2001 14:17, Peter Dalgaard BSA wrote:
> 
> 
> > This seems to work, save for a (sort of spurious) warning that 6000 is
> > not a valid replacement value for the factor column:
> >
> > x[,]<-lapply(x,function(z){z[z==6]<-6000;z})
> >
> > (Why the comma? Search me...)
> >
> 
> Works also without the comma:
> 
> x <- data.frame(lapply(x,function(x) {x[x==6]<-6000;x}))
> 
> but still gives the warning.

Yes. I was trying to avoid the data.frame step by assigning the list
coming out of lapply back to the original frame, thus keeping all
attributes and class info.

You can get rid of the warning with 

x[2:3]<-lapply(x[2:3],function(z){z[z==6]<-6000;z})

or generically

s <-sapply(x,is.numeric)
x[s] <- lapply(x[s],function(z){z[z==6]<-6000;z})

Hmmmm... How about

recode<-function(x,value,replacement){
	x[if (is.na(value)) is.na(x) else x==value] <- replacement
	x
}
s <-sapply(x,is.numeric)
x[s] <- lapply(x[s], recode, 6, 6000)
x[s] <- lapply(x[s], recode, NA, 1000)

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