0

谁能向我解释一下(R 3.0.1)?为什么向量的元素与向量本身的类不同?不知何故,units 属性并没有传递到元素。提前谢谢了。

> x <- as.difftime( 0.5, units='mins' )
> print(class(x))
[1] "difftime"

> y <- as.difftime( c(0.5,1,2), units='mins' )
> print(class(y))
[1] "difftime"

> for (z in y) print(class(z))
[1] "numeric"
[1] "numeric"
[1] "numeric"
4

2 回答 2

2

There is a [.difftime version of the [function but no [[.difftime version of [[

> `[.difftime`
function (x, ..., drop = TRUE) 
{
    cl <- oldClass(x)
    class(x) <- NULL
    val <- NextMethod("[")
    class(val) <- cl
    attr(val, "units") <- attr(x, "units")
    val
}
<bytecode: 0x1053916e0>
<environment: namespace:base>

So the for function is pulling items from the y-object with [[ and it is loosing its attributes. This would let you get what you expected to see:

> for(i in seq_along(y) ){print(y[i])}
Time difference of 0.5 mins
Time difference of 1 mins
Time difference of 2 mins
> for(i in seq_along(y) ){print(class(y[i]))}
[1] "difftime"
[1] "difftime"
[1] "difftime"
于 2013-09-16T20:45:42.387 回答
0

class对象的存储方式不必与该对象的元素的存储方式相同。从帮助页面class

许多 R 对象都有一个类属性,一个字符向量给出对象继承的类的名称。如果对象没有类属性,则它具有隐式类、“矩阵”、“数组”或 mode(x) 的结果(除了整数向量具有隐式类“整数”)。

所以如果你这样做:

y <- as.difftime( c(0.5,1,2), units='mins' )

# 'typeof' determines the (R internal) type or storage mode of any object
typeof( y )
# [1] "double"

# And mode: Modes have the same set of names as types (see typeof) except that
# types "integer" and "double" are returned as "numeric".
mode( y )
# [1] "numeric"

class是一种编程结构,它允许您执行以下操作:

# Integer vector
x <- 1:5
#  Set the class with 'class<-'
class(x) <- "foo"

#  Which is correctly returned by 'class'
class(x)
# [1] "foo"

#  But our elements are still integers...
typeof(x)
[1] "integer"
于 2013-09-16T20:52:09.327 回答