Invalid factor level with rbind to data frame
When you do
c("one","lala",1)
this creates a vector of strings. The 1
is converted to character type,
so that all elements in the vector are the same type.
Then rbind(a,b)
will try to combine a
which is a data frame and b
which is a character vector and this is not what you want.
The way to do this is using rbind
with data frame objects.
a <- NULL
b <- data.frame(A="one", B="lala", C=1)
d <- data.frame(A="two", B="lele", C=2)
a <- rbind(a, b)
a <- rbind(a, d)
Now we can see that the columns in data frame a
are the proper type.
> lapply(a, class)
$A
[1] "factor"
$B
[1] "factor"
$C
[1] "numeric"
>
Notice that you must name the columns when you create the different data
frame, otherwise rbind
will fail. If you do
b <- data.frame("one", "lala", 1)
d <- data.frame("two", "lele", 2)
then
> rbind(b, d)
Error in match.names(clabs, names(xi)) :
names do not match previous names