Reputation: 2834
I am currently reading R Cookbook. A statement made in the book says the following:
"A vector can contain etiher numbers, strings, or logical but not mixture."
I wanted to test this out so I created the following vector:
u <- c("c",1,TRUE)
u
[1] "c" "1" "TRUE"
This looks like it changed everything to a string. I then did the following:
u <- c(TRUE,0)
u
[1] 1 0
So it looks like when there is a mixture of types, they are all converted to a similar type. My question is how does R determine which type?
Upvotes: 1
Views: 203
Reputation: 303
You might find the Coercion section of the Advanced R book helpful. The elements are coerced from least to most flexible type (logical > integer > double > character).
Upvotes: 1
Reputation: 75545
As described in this article, the bigger type wins. That is, the type that can represent more wins.
In your first example, character can represent all of the other three, so it coerces everyone to character.
The second case the integer is bigger than the logical.
This answer lists the full hierarchy.
raw < logical < integer < double < complex < character < list
Upvotes: 2