一系列数字的类

时间:2013-08-05 00:30:34

标签: r

我可以用三种方式之一创建一系列数字:

> 1:4
[1] 1 2 3 4

> seq(1,4)
[1] 1 2 3 4

> c(1,2,3,4)
[1] 1 2 3 4

但为什么c()会返回另一个类?

> class(1:4)       
[1] "integer"

> class(seq(1,4))
[1] "integer"

> class(c(1,2,3,4))
[1] "numeric"

编辑:在讨论中添加seq()

1 个答案:

答案 0 :(得分:13)

help(":")的Value部分告诉冒号运算符返回的内容。它说:

  如果from是整数值,则

...将是整数类型,并且结果可以在R整数类型中表示。

因此,如果from可以表示为整数,则整个向量被强制转换为整数

> class(1.0:3.1)
[1] "integer"
> 1.0:3.1
[1] 1 2 3

通常在R中,1numeric。如果您需要integer,则必须附加L

> class(1)
[1] "numeric"
> class(1L)
[1] "integer"

此外,c将所有参数“强制转换为返回值类型的公共类型”(来自?c)。什么类型“是从层次结构中最高类型的组件确定的NULL< raw< logical< integer< double< complex< character< list< expression。”

因此,如果c的任何参数比integer更通用,则整个矢量将被强制转换为更一般的类。

> class(c(1L, 2L, 3L, 4L))
[1] "integer"
> class(c(1L, 2, 3L, 4L)) # 2 is numeric, so the whole vector is coerced to numeric
[1] "numeric"
> class(c(1L, 2, "3L", 4L)) # "3L" is character, so the whole vector is coerced to character
[1] "character"

Re:seq案例,

seq(1, 4)1:4

中所述的?seq相同

seq(from,to)“生成序列,从+/- 1,...,到(与from:to相同)”

相关问题