[R] rbind data.frames with character vectors?

Spencer Graves spencer.graves at pdf.com
Mon Mar 31 18:11:34 CEST 2003


"rbind(A, B)" converts character columns of A and B to factors.  This 
means that "A <- rbind(A, B)" generates NAs unless the character strings 
in B are already levels of the corresponding columns of A.

I've got a work-around, but I'm not happy with it.  What do you suggest?

Example:

 > A <- data.frame(a=1)
 > A$b <- "A"
 > B <- data.frame(a=2)
 > B$b <- "B"
 > sapply(A, data.class)
           a           b
   "numeric" "character"
 > AB <- rbind(A,B)
 > sapply(AB, data.class)
         a         b
"numeric"  "factor"
 > C. <- data.frame(a=3)
 > C.$b <- "C"
 > rbind(AB, C.)
     a    b
1   1    A
11  2    B
111 3 <NA>
Warning message:
invalid factor level, NAs generated in: "[<-.factor"(*tmp*, ri, value = 
"C")
 > sapply(rbind(AB, C.), data.class)
         a         b
"numeric"  "factor"
Warning message:
invalid factor level, NAs generated in: "[<-.factor"(*tmp*, ri, value = 
"C")

Thanks,
Spencer Graves
p.s.  This example produces the desired result in S-Plus 2000 and 6.1 
Professional for Windows 2000.



More information about the R-help mailing list