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

为什么使用names()函数时*apply返回命名对象而不是值的向量?

r
  •  0
  • gss  · 技术社区  · 4 年前

    我确信在使用此代码时会得到字符向量:

    vec <- c(a = 1, b = 2)
    vec
    #> a b 
    #> 1 2
    sapply(vec, names)
    #> $a
    #> NULL
    #> 
    #> $b
    #> NULL
    

    list 在这种情况下)与 NULL 值,而不是-正如我所想-返回的值 names()

    1 回复  |  直到 4 年前
        1
  •  3
  •   G. Grothendieck    4 年前

    # pass names and values
    f <- function(name, value)  sprintf("%s: %d", name, value)
    mapply(f, names(vec), vec)
    ##      a      b 
    ## "a: 1" "b: 2" 
    
    # pass names but look up values
    f2 <- function(name) sprintf("%s: %d", name, vec[name])
    sapply(names(vec), f2)
    ##      a      b 
    ## "a: 1" "b: 2" 
    
    # pass index and lookup both names and values
    f3 <- function(i) sprintf("%s: %d", names(vec)[i], vec[i])
    sapply(seq_along(vec), f3)
    ##      a      b 
    ## "a: 1" "b: 2" 
    
    # if values are unique can pass values and look up names
    f4 <- function(value) sprintf("%s: %d", names(vec)[match(value, vec)], value)
    sapply(vec, f4)
    ##      a      b 
    ## "a: 1" "b: 2" 
    
    # convert to a 2 column data frame w names (ind) and values  
    spl <- split(stack(vec), seq_along(vec))  
    sapply(spl, with, sprintf("%s: %d", ind, values))
    ##      a      b 
    ## "a: 1" "b: 2"