Skip to content
Prev 308451 / 398506 Next

replacing rows data.frame

Hello,

Your problem comes from the fact that as new values are inserted in 
'alloc' the column alloc$agi keeps changing (obvious!) therefore R can't 
know all the factor levels beforehand. Therefore the values inserted are 
the numeric codes of the original factor. Since your example doesn't 
run, I've made up a dataset. Try to see what happens.


x <- data.frame(A = letters[1:10], B = 1:10)
str(x)

y <- data.frame(matrix(nrow=5, ncol=2))
colnames(y) <- colnames(x)

for(i in 1:10){
     if(i %% 2 == 0){  # example condition
         y[i/2, 1] <- as.character(x[i, 1])  # the factor column
         y[i/2, -1] <- x[i, -1]  # all but 1st column
     }
}
y$A <- factor(y$A)  # in the end we know the levels.
str(y)


Likewise, you must first fill in the column with character values then, 
in the end, coerce to factor.

Hope this helps,

Rui Barradas
Em 19-10-2012 12:06, evelyne escreveu: