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

関数の[.difftimeバージョンはありますが、バージョンはありません[[[.difftime[[

> `[.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>

そのため、for関数は y オブジェクトからアイテムをプルして[[おり、その属性を失っています。これにより、期待どおりの結果が得られます。

> 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 オブジェクトには class 属性があります。これは、オブジェクトが継承するクラスの名前を指定する文字ベクトルです。オブジェクトがクラス属性を持たない場合は、暗黙のクラス、"matrix"、"array"、または mode(x) の結果を持ちます (整数ベクトルには暗黙のクラス "integer" がある場合を除く)。

したがって、次のようにします。

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 に答える