Connor Watson
Connor Watson

Reputation: 115

vector - character/integer class (under the hood)

Starting to learn R, and I would appreciate some help understanding how R decides the class of different vectors. I initialize vec <- c(1:6) and when I perform class(vec) I get 'integer'. Why is it not 'numeric', because I thought integers in R looked like this: 4L

Also with vec2 <- c(1,'a',2,TRUE), why is class(vec2) 'character'? I'm guessing R picks up on the characters and automatically assigns everything else to be characters...so then it actually looks like c('1','a','2','TRUE') am I correct?

Upvotes: 3

Views: 112

Answers (1)

www
www

Reputation: 39154

Type the following, you can see the help page of the colon operator.

?`:`

Here is one paragraph.

For numeric arguments, a numeric vector. This will be of type integer if from is integer-valued and the result is representable in the R integer type, otherwise of type "double" (aka mode "numeric").

So, in your example c(1:6), since 1 for the from argument can be representable in R as integer, the resulting sequence becomes integer.

By the way, c is not needed to create a vector in this case.

For the second question, since in a vector all the elements have to be in the same type, R will automatically convert all the elements to the same. In this case, it is possible to convert everything to be character, but it is not possible to convert "a" to be numeric, so it results in a character vector.

Upvotes: 4

Related Questions