zoukankan      html  css  js  c++  java
  • R中的list的少有人知的地方

    关于list和atomic一些比较杂的知识, 主要来自Advanced R, 我觉得很有条理了, 但原文写得很好. 但这只是其中一部分. 另一部分在另一篇.

    为什么is.vector(list(a=1,b=2))会返回TRUE?

    R中的vector分为两类,atomic vector和list(出自). 要想区分atomic和list,可以使用is.atomic和is.list函数.

    二者的区别在于,前者元素类型必须相同,后者可以不同. 前者的代表是向量和矩阵,后者的代表是list和数据框.

    list也被称为recursive vectors.

    x <- list(list(list(list())))
    str(x)
    #> List of 1
    #>  $ :List of 1
    #>   ..$ :List of 1
    #>   .. ..$ : list()
    is.recursive(x)
    #> [1] TRUE
    

    如何得到atomic vector? Coercion

    例一:

    c(TRUE,"abcs",1.23,1)
    

    类型不统一怎么办? 隐式类型转换.

    学过c的肯定不陌生. R的转换顺序是(也就是强弱顺序):

    logical<integer<numeric/double<character, 这是符合直观的.

    关于numeric/double的区别, 这里有写.

    c()对list的效果

    c() will combine several lists into one. If given a combination of atomic vectors and lists, c() will coerce the vectors to lists before combining them.

    把几个list合成一个.

    但是怎么合成? 是元素合在一起? 还是简单的得到一个list, 它的元素是这几个list?

    > l1<-list(a=1,b=2)
    > l2<-list(c=3,d=4)
    > c(l1,l2)
    $a
    [1] 1
    
    $b
    [1] 2
    
    $c
    [1] 3
    
    $d
    [1] 4
    

    看来是前者.

    c(list,c(1,2,3)), 会将c(1,2,3)先转换为一个list

    > l1<-list(a=1,b=2)
    > c(l1,c(3,4))
    $a
    [1] 1
    
    $b
    [1] 2
    
    [[3]]
    [1] 3
    
    [[4]]
    [1] 4
    

    后面两个元素没有名字, 因此就用[[3]]表示.

    typeof(NA) # logical
    k <- c(NA,1L,3L)
    m <- c(NA,1,3)
    n <- c(NA,1,"a")
    typeof(k[1]) # integer
    typeof(m[1]) # double
    typeof(n[1]) # character
    

    list转换为atomic

    The typeof() a list is list. You can test for a list with is.list() and coerce to a list with as.list(). You can turn a list into an atomic vector with unlist(). If the elements of a list have different types, unlist() uses the same coercion rules as c().

    unlist, 以及会用到coercion rules前面已经说了.

  • 相关阅读:
    HIHO线段树(成段)
    HIHO 线段树(单点)
    POJ 3468
    HDU 1754
    HDU 1698
    HDU 5119
    HDU 1394
    HDU 1166
    DZY Loves Chessboard
    谷歌Cookies无法写入
  • 原文地址:https://www.cnblogs.com/Tokubara/p/13810624.html
Copyright © 2011-2022 走看看