rsapply

Use name of the element inside the function of sapply


sapply can use names of the original list to name the elments of the output. However it is a bit unclear to me how it does so:

> base::sapply
function (X, FUN, ..., simplify = TRUE, USE.NAMES = TRUE) 
{
    FUN <- match.fun(FUN)
    answer <- lapply(X = X, FUN = FUN, ...)
    if (USE.NAMES && is.character(X) && is.null(names(answer))) 
        names(answer) <- X # Here it is
    if (!identical(simplify, FALSE) && length(answer)) 
        simplify2array(answer, higher = (simplify == "array"))
    else answer
}

However I want also to use the name of the original elements of the list to be used inside the function passed to sapply. How can I use the name of the element of the list I am iterating on in the function?

My only workaround has been using a for loop:

for (x in seq_along(list)) {
  y <- FUN(list[[x]]) 
  method(y) <- names(list)[x]
}

Solution

  • If you want to use both the names and the values of the list, you could pass the names as an argument and use them to access the values. Here an example:

    score <- list(name1 = 1, name2 = 2)
    sapply(names(score), function(name) score[[name]]*nchar(name))
    

    As you see the function(name) score[[name]]*nchar(name) uses both the name and the value score[[name]].