[R] lapply() not converting columns to factors (no error message)

Peter Dalgaard P.Dalgaard at biostat.ku.dk
Mon Nov 16 15:30:17 CET 2009


A Singh wrote:
> Dear List,
> 
> I'm having a curious problem with lapply(). I've used it before to
> convert a subset of columns in my dataframe, to factors, and its worked.
> But now, on re-running the identical code as before it just doesn't
> convert the columns into factors at all.
> 
> As far as I can see I've done nothing different, and its strange that it
> shouldn't do the action.
> 
> Has anybody come across this before? Any input on this strange issue
> much appreciated..
> 
> Hope I haven't missed something obvious.
> 
> Thanks a lot,
> 
> Aditi
> 
> (P.s.- I've tried converting columns one by one to factors this time,
> and that works.
> 
>> P1L55<-factor(P1L55)
>> levels(P1L55)
>> [1] "0" "1"
> 
> Code:
> 
> prm<-read.table("P:\\.....  .csv", header=T, ...sep=",", ...)
> 
> prmdf<-data.frame(prm)
> 
> prmdf[2:13]<-lapply(prmdf[2:13], factor) ## action performed, no error
> message
> 
> ##I tried to pick random columns and check
> 
>> levels(P1L55)
>> NULL
> 
>> is.factor(P1L96)
>> FALSE

Make sure that you are looking in the same object that you changed. E.g.

attach(prmdf)
prmdf[2:13]<-lapply(prmdf[2:13], factor)
levels(P1L55)

is not going to work

levels(prmdf$P1L55)

should, or attaching _after_ the change. Also, make sure that you don't
have P1L55 et al. sitting in the global enviromnent.

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