Colonel Beauvel
Colonel Beauvel

Reputation: 31181

Adding a line with rbind changes the nature of columns in data.table in R

I am taking a data.table:

DT <- data.table(num=c(1,4,6,7,8,12,13, 15), let=rep(c("A","B"), each=4))

An then I have the following result:

> sapply(DT, class)
    num         let 
"numeric" "character" 

Which is ok.

Then, adding a line:

DT<-rbind(DT, as.list(c(8, "B")))

And then:

> sapply(DT, class)
    num         let 
"character" "character" 

I find this vicious that R changed the first column type to character and did not expect it ... I can change the column to numeric afterwards but it's painfull if I have to check after every insert.

Is there's a way to add line without this drawback?

Upvotes: 5

Views: 1783

Answers (1)

Simon O&#39;Hanlon
Simon O&#39;Hanlon

Reputation: 60000

Your first problem stems from your use of c, the function to combine arguments into a vector. This produces an atomic vector (in this case - you are combining two length one atomic vectors, namely the vector 8 and the vector "B") which may be of only one data type, so in your example c(8,"B") is evaluated first, resulting in:

str( c(8, "B") )
# chr [1:2] "8" "B"

Therefore you should not expect any other result!

Upvotes: 7

Related Questions