Vivek - 4 months ago 24

R Question

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"

>

`integer`

`L`

`x`

`y`

`numeric`

However, without vector things go as usual:

`> a <-3`

> class(a)

[1] "numeric"

> b <- 3L

> class(b)

[1] "integer"

Answer Source

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"
```