Vivek - 1 year ago 44
R Question

# Object conversion with vectors

I run given code:

``````> mean(as.numeric(x <- 1:4))
[1] 2.5
> class(x)
[1] "integer"
>
> x <- 2:5
> class(x)
[1] "integer"
> as.numeric(x)
[1] 2 3 4 5
> class(x)
[1] "integer"
>
``````

Query - As far as I have studied for an object to behave like an
`integer`
it has to be assigned
`L`
in the end, but over here, I see completely a different story. So, why the classes of
`x`
and
`y`
are not
`numeric`
?

However, without vector things go as usual:

``````> a <-3
> class(a)
[1] "numeric"
> b <- 3L
> class(b)
[1] "integer"
``````

If we check the `?":"`, it is already described

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

Here, `2` and `5` are integers and so the sequence will also be `integer` call. Of course type promotion is there in dynamic languages as opposed to static languages

Also, check the output of

``````class(seq(2, 5))
#[1] "integer"
class(seq(2.0, 5.0))
#[1] "integer"
class(seq(2.0, 5.0, by = 1.0))
#[1] "numeric"
class(seq(2, 5, by = 1.0))
#[1] "numeric"
class(seq(2, 5, by = 1))
#[1] "numeric"
class(seq(2, 5, by = 1L))
#[1] "numeric"
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download