Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid factor level with rbind to data frame

Tags:

r

I'm new in R and I don't know how exacly adding row in data frame. I add two vectors:

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

I want add this to data.frame called a.

a<-rbind(a,b)

now I have one correct row

      A       B      C
1    one   lala      1

next I add

a<-rbind(a,d)

and result is:

      A       B       C
1    one    lala      1
2     NA      NA      NA

and console write me warning messages: invalid factor level, NA generated. What I do wrong or what is better simple way to add new line. But I don't want in start create full data.frame. I want adding lines.

like image 775
Nejc Galof Avatar asked Aug 13 '14 11:08

Nejc Galof


People also ask

What is invalid factor level in R?

This warning occurs when you attempt to add a value to a factor variable in R that does not already exist as a defined level.

What is the function of Rbind () in R programming?

Syntax of the rbind() function rbind(): The rbind or the row bind function is used to bind or combine the multiple group of rows together.

What is the use of Rbind () and Cbind () in R?

cbind() and rbind() both create matrices by combining several vectors of the same length. cbind() combines vectors as columns, while rbind() combines them as rows.

What is the meaning of Rbind ()?

rbind() function in R Language is used to combine specified Vector, Matrix or Data Frame by rows. Syntax: rbind(x1, x2, …, deparse.level = 1)


1 Answers

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
like image 150
Ernest A Avatar answered Oct 05 '22 02:10

Ernest A