I was surprised to see that R will coerce factors into a number when concatenating vectors. This happens even when the levels are the same. For example:
>
Based on the other answers which use converting to character I'm using the following function to concatenate factors:
concat.factor <- function(...){
as.factor(do.call(c, lapply(list(...), as.character)))
}
You can use this function just as you would use c
.
For this reason I prefer to work with factors inside data.frames:
df <- data.frame(facs = as.factor(
c("i", "want", "to", "be", "a", "factor", "not", "an", "integer") ))
and subset it using subset() or dplyr::filter() etc. rather than row indexes. Because I don't have meaningful subset criteria in this case, I will just use head() and tail():
df1 <- head(df, 4)
df2 <- tail(df, 2)
Then you can manipulate them quite easily, e.g.:
dfc <- rbind(df1, df2)
dfc$facs
#[1] i want to be an integer
#Levels: a an be factor i integer not to want