I have a problem with the way R coerces variable types when using rbind
of two data.frames
with NA
values. I illustrate by example:
x<-factor(sample(1:3,10,T))
y<-rnorm(10)
dat<-data.frame(x,y)
NAs<-data.frame(matrix(NA,ncol=ncol(dat),nrow=nrow(dat)))
colnames(NAs)<-colnames(dat)
Now the goal is to append dat
and NAs
while keeping the variable types factor
and numeric
of x
and y
. When I give:
dat_forward<-rbind(dat,NAs)
is.factor(dat_forward$x)
this works fine. However the backward direction using rbind
fails:
dat_backward<-rbind(NAs,dat)
is.factor(dat_backward$x)
is.character(dat_backward$x)
Now x
is coerced to character level. I am confused - can't it stay factor type even if I use the other order of binding? What would be a straight forward change to my code to reach my goal?