简体   繁体   English

向量的对象转换

[英]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. 查询-就我研究的对象的行为而言,它必须像integer一样,最后必须赋予L ,但在这里,我看到的是完全不同的故事。 So, why the classes of x and y are not numeric ? 那么,为什么xy的类不是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"). 如果from是整数值,并且结果可以用R整数类型表示,则它将是整数类型,否则将是“ double”类型(又名“ numeric”模式)。

Here, 2 and 5 are integers and so the sequence will also be integer call. 在这里, 25是整数,因此序列也将是integer调用。 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM