Invalid factor level bound to data frame

I am new to R and I don't know how to add a row in a data frame. I add two vectors:

b=c("one","lala",1) d=c("two","lele",2) 

I want to add this to a data.frame called a.

 a<-rbind(a,b) 

I now have one correct line

  ABC 1 one lala 1 

next I add

 a<-rbind(a,d) 

and the result:

  ABC 1 one lala 1 2 NA NA NA 

and console write me warning messages: invalid factor level generated by NA. What am I doing wrong or what is better than an easy way to add a new line. But I do not want to start creating a complete data.frame. I want to add lines.

+6
source share
1 answer

When you do

 c("one","lala",1) 

this creates a row vector. 1 converted to a character type, so that all elements in the vector are of the same type.

Then rbind(a,b) will try to combine a , which is the data frame, and b which is the character symbol, and that is not what you want.

A way to do this is with 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 see that the columns in data frame a are the correct type.

 > lapply(a, class) $A [1] "factor" $B [1] "factor" $C [1] "numeric" > 

Please note that you must specify columns when creating 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 
+6
source

Source: https://habr.com/ru/post/973760/


All Articles