[R] assign column classes when creating a data frame from several vectors

kamokoi kamokoi at gmail.com
Wed Jan 30 03:02:28 CET 2008


R-helpers,

Thanks in advance for your help.  I am an R newbie and I am having trouble
figuring out the easiest/most efficient way to assign classes to columns in
a newly created data frame.  R seems to want to convert everything to a
factor when I use the cbind function to compile vectors into a data frame.  

ID<-seq(1,10,1)
TREAT<-c(rep("B",5),rep("G",5))
T1<-rnorm(10,50,10)
T2<-rnorm(10,15,10)
data<-as.data.frame(cbind(ID,TREAT,T1,T2))

data

   ID TREAT               T1                T2
1   1     B  41.506987139726  20.0964019326073
2   2     B 53.7814271299636   4.9049787919397
3   3     B  54.118333111305  18.2182330777312
4   4     B 48.8591282265369  12.4561774992591
5   5     B 32.3160291908524  23.6665858869752
6   6     G 52.3181626145907 -4.60173207209386
7   7     G 53.4170845444393  2.30744010208809
8   8     G 60.4200675102018  10.9954680147326
9   9     G 42.6264529901835  9.22980548637643
10 10     G 40.2748346897501  14.2458580129253

sapply(data,class)
      ID    TREAT       T1       T2 
"factor" "factor" "factor" "factor" 

The only way I can find to get around this is to use stringsAsFactors=FALSE
and then assign classes to each of the columns individually.

data<-as.data.frame(cbind(ID,TREAT,T1,T2), stringsAsFactors=F)
data$ID<-as.factor(data$ID)
data$TREAT<-as.factor(data$TREAT)
data$T1<-as.numeric(data$T1)
data$T2<-as.numeric(data$T2)
sapply(data,class)
       ID     TREAT        T1        T2 
 "factor"  "factor" "numeric" "numeric" 

Is there a more efficient way to do the same thing.

Thanks for your help.

 

-- 
View this message in context: http://www.nabble.com/assign-column-classes-when-creating-a-data-frame-from-several-vectors-tp15174042p15174042.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list