5

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?

Arun
  • 116,683
  • 26
  • 284
  • 387
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
  • 2
    Doing `rbind(dt, list(8,"B"))` is probably what you are looking for. (2nd comment to this post: http://stackoverflow.com/questions/16652533/insert-a-row-in-a-data-table). –  Jun 19 '14 at 09:09
  • Exactly, I should have using simply `list` ... I took the way to add a line on this link actually! Thks. – Colonel Beauvel Jun 19 '14 at 09:20

1 Answers1

7

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!

Simon O'Hanlon
  • 58,647
  • 14
  • 142
  • 184
  • 1
    Excellent answer to my mistake where I confused two data types in a structure which does only allow one ... – Colonel Beauvel Jun 19 '14 at 09:30
  • 1
    @ColonelBeauvel np. And +1 for Pascals comment above which shows you how to circumvent this. BTW to add say two rows you can use e.g. `rbind(dt, list( 8:9 , c( "A","B") ) )`. – Simon O'Hanlon Jun 19 '14 at 09:32