Filter values from list in R

前端 未结 3 1056
死守一世寂寞
死守一世寂寞 2021-02-13 09:37

I want to calculate the mean of a list of named numbers. There are numeric(0) values that I first want to remove. Also, I would like to retrieve which elements of

相关标签:
3条回答
  • 2021-02-13 09:44

    Another solution using the Filter function from base R:

    mean(unlist(Filter(is.numeric, l)))
    
    0 讨论(0)
  • 2021-02-13 09:45

    Unlisting will pull out just the numeric entries in a single vector which you can call mean on, so try:

    mean(unlist(r["gg",]))
    
    0 讨论(0)
  • 2021-02-13 09:48
    ## Example list
    
    l <- list(n1=numeric(0), n2="foo", n3=numeric(0), n4=1:5)
    
    ## Filter out elements with length 0
    
    l[lapply(l, length) > 0]
    
    
    $n2
    [1] "foo"
    
    $n4
    [1] 1 2 3 4 5
    
    
    ## Get names of elements with length 0
    
    names(l)[lapply(l, length) == 0]
    
    [1] "n1" "n3"
    
    0 讨论(0)
提交回复
热议问题