Here's a fairly simple way to get the column classes right:
x <- rbind(dat[1,], NAs, dat)[-1,]
str(x)
# $ x: Factor w/ 3 levels "1","2","3": NA NA NA NA NA NA NA NA NA NA ...
# $ y: num NA NA NA NA NA NA NA NA NA NA ...
More generally, if you are really needing this often, you could create an rbind
-like function that takes an additional argument indicating the data.frame to whose column classes you'd like to coerce all of the others' columns:
myrbind <- function(x, ..., template=x) {
do.call(rbind, c(list(template[1,]), list(x), list(...)))[-1,]
}
str(myrbind(NAs, dat, template=dat))
# 'data.frame': 20 obs. of 2 variables:
# $ x: Factor w/ 3 levels "1","2","3": NA NA NA NA NA NA NA NA NA NA ...
# $ y: num NA NA NA NA NA NA NA NA NA NA ...
## If no 'template' argument is supplied, myrbind acts just like rbind
str(myrbind(dat, NAs))
# 'data.frame': 20 obs. of 2 variables:
# $ x: Factor w/ 3 levels "1","2","3": 3 3 3 3 2 3 1 1 3 2 ...
# $ y: num 0.303 1.77 -1.38 1.731 0.033 ...