Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 961
Connor Watson Avatar asked Apr 19 '26 06:04

Connor Watson


1 Answers

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.

like image 98
www Avatar answered Apr 21 '26 23:04

www



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!