Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/hibernate/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 向量的元素与向量不具有相同的类_R - Fatal编程技术网

R 向量的元素与向量不具有相同的类

R 向量的元素与向量不具有相同的类,r,R,有人能给我解释一下吗(R3.0.1)?为什么向量的元素与向量本身没有相同的类?不知何故,“单位”属性不会向下传递到元素。非常感谢 > 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

有人能给我解释一下吗(R3.0.1)?为什么向量的元素与向量本身没有相同的类?不知何故,“单位”属性不会向下传递到元素。非常感谢

> 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"
>x打印(类别(x))
[1] “扩散时间”
>y打印(y类))
[1] “扩散时间”
>用于(z/y)打印(类别(z))
[1] “数字”
[1] “数字”
[1] “数字”

[
函数的
[.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>

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

许多R对象都有一个类属性,一个字符向量,给出对象继承的类的名称。如果对象没有类属性,它有一个隐式类,“矩阵”、“数组”或模式(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"

在这种情况下,您可能想看看
y[1]
y[[1]]
之间的区别。的可能重复不同意重复的接近投票。
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"
# 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"