Forzan
Forzan

Reputation: 137

Managing different decimals in a vector - R

I need to have a list where the first number have a decimal, but the others don't.

Here is an example :

to_add = 1.5
main = c(3,5,7 , 9, 11, 13 ,15, 17, 19)

tot = c(to_add,main)

tot
#The problem :
# [1]  1.5  3.0  5.0  7.0  9.0 11.0 13.0 15.0 17.0 19.0

Don't really know why but R display a ".0" even though, if we take a look individually, it doesn't :

tot[2]
# [1]  3

What I do after that is putting this list in the axis of a graph :

axis(1, at=tot)

If I gave it a list of character, it will convert with the same display as above.

Upvotes: 0

Views: 416

Answers (3)

harre
harre

Reputation: 7287

In order to "solve" your issue as described in the other posts (e.g. if you need the numbers for presentation), you could convert the integers and real numbers into character types before concatenating (= they will be stored as strings from then on).

tot <- c(as.character(to_add), as.character(main))

Output:

str(tot)
chr [1:10] "1.5" "3" "5" "7" "9" "11" "13" "15" "17" "19"

Update 27/7:

To use it for a plot, you'll want to use this as the label argument too.

The at-argument will automatically convert it to numerics, but you might want to keep one for the ticks and for the labels depending on the use-case.

plot(tot, 1:length(tot))
axis(1, at = tot, label = tot)

enter image description here

Upvotes: 1

mmrabe
mmrabe

Reputation: 186

There are actually two reasons:

The first is coercion, as already mentioned by statnet22 above. When you combine elements of different types in a single vector in R, it is cast to a common data type. You cannot have elements of different types in a vector (but a list would work).

Secondly, even if R doesn’t display a decimal number, it may actually be one:

b1 = c(3L, 5L, 7L, 9L, 11L, 13L, 15L, 17L, 19L)
b2 = as.integer(c(3, 5, 7, 9, 11, 13, 15, 17, 19))
b3 = c(3, 5, 7, 9, 11, 13, 15, 17, 19) # == main

All three vectors b1, b2, and b3 are displayed as:

# [1]  3  5  7  9 11 13 15 17 19

Only b1 and b2 are actually integer vectors though:

str(b1)
# int [1:9] 3 5 7 9 11 13 15 17 19
str(b2)
# int [1:9] 3 5 7 9 11 13 15 17 19
str(b3)
# num [1:9] 3 5 7 9 11 13 15 17 19

Nevertheless, when you add a real number such as 1.5 to the vector, all of them will become “numeric” vectors (see coercion).

Upvotes: 1

statnet22
statnet22

Reputation: 446

Have a further read on coercion here, but the short answer as to why this is happening is that all elements of a vector must be of the same type:

All elements of an atomic vector must be the same type, so when you attempt to combine different types they will be coerced to the most flexible type. Types from least to most flexible are: logical, integer, double, and character.

Upvotes: 2

Related Questions