7

我可以通过以下三种方式之一创建一个数字序列:

> 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()到讨论中。

4

1 回答 1

13

的值部分help(":")告诉冒号运算符返回什么。它说:

... 如果 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"

回复:seq案例,

seq(1, 4)1:4中所述相同?seq

seq(from, to) "生成序列 from, from+/-1, ..., to (与 from:to 相同)"

于 2013-08-05T00:40:27.990 回答