Home > Software engineering >  Managing different decimals in a vector - R
Managing different decimals in a vector - R

Time:07-26

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

CodePudding user response:

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.

CodePudding user response:

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).

CodePudding user response:

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"
  • Related