代码之家  ›  专栏  ›  技术社区  ›  sayth

rc()创建一个容器,该容器与连接的对象具有相同的类。对的?

r
  •  0
  • sayth  · 技术社区  · 5 年前

    如果我连接一个数字(双精度):

    x <- c(0.5,0.6)
    

    > x
    [1] 0.5 0.6
    > attributes(x)
    NULL
    > x
    [1] 0.5 0.6
    > type(x)
    Error in type(x) : could not find function "type"
    > typeof(x)
    [1] "double"
    > mode(x)
    [1] "numeric"
    

    我有点困惑,因为使用c()时创建的容器与连接的对象的类型相同。我的看法是正确的还是根本错误的?

    0 回复  |  直到 5 年前
        1
  •  2
  •   G. Grothendieck    5 年前

    数值向量是R中的原子对象,而不是容器,下面的3个对象都是具有类的数值向量 "numeric" 最后两个是一样的。

    0.5 0.6 放入容器 c(0.5, 0.6) 0.5 用向量 0.6 .

    # these are all numeric vectors
    c(0.5,0.6)
    c(0.5)
    9.5
    
    # the last two objects above are identical
    identical(c(0.5), 0.5)
    ## [1] TRUE
    
    # they are all of class "numeric"
    class(c(0.5, 0.6))
    ## [1] "numeric"
    class(0.5)
    ## [1] "numeric"
    

    列表是复杂的对象,可以看作容器,但不能看作数字向量。

    # numeric vectors, but not lists, are atomic
    is.atomic(c(0.5, 0.6))
    ## [1] TRUE
    is.atomic(list(0.5, 0.6))
    ## [1] FALSE
    
        2
  •  3
  •   Jon Spring    5 年前

    我不确定我能完全回答,但注意到R中没有标量,只有长度为1的向量可能会有所帮助。当你使用 c()

    x <- 0
    typeof(x)
    #[1] "double"
    length(x)
    #[1] 1         # Now we have a double vector of length one.
    
    y <- c(0)
    typeof(y)
    #[1] "double"
    length(y)
    #[1] 1         # Using c(), we made another double vector also of length one.
    
    identical(x, y)  # are x and y identical objects?
    #[1] TRUE        #  yep!
    
    z <- c(0, 0)   # Now, use c() with two values
    typeof(z)
    #[1] "double"
    length(z)
    #[1] 2          # now we have a double vector of length two.
    
    identical(x, z)
    [1] FALSE