After combining vectors into a matrix, how to keep the original vector attribute (unchanged)

below R-code shows an example of a combination of vectors, after that the vector attribute "c" changed to symbol. how to make it still support the attribute as numeric?

a='aa';b='bb';c=c(1,2,3,4,5)
dd=data.table(cbind(a,b,c));dd;class(dd);class(a);class(b);typeof(dd$c)

      

works like below:

> a='aa';b='bb';c=c(1,2,3,4,5)
> dd=data.table(cbind(a,b,c));dd;class(dd);class(a);class(b);typeof(dd$c)
    a  b c
1: aa bb 1
2: aa bb 2
3: aa bb 3
4: aa bb 4
5: aa bb 5
[1] "data.table" "data.frame"
[1] "character"
[1] "character"
[1] "character"

      

see typeof (dd $ c) has been changed to "character" rather than numeric. how to keep it as original attribute?

+3


source to share


1 answer


The reason is that it is cbind

converted to matrix

, and matrix

can only contain one class. If there is one element character

, it converts the entire matrix to character

. Better do



data.table(a, b, c)

      

+4


source







All Articles