I was sure I will get vector of characters when using this code:
vec <- c(a = 1, b = 2)
vec
#> a b
#> 1 2
sapply(vec, names)
#> $a
#> NULL
#>
#> $b
#> NULL
But it returns named object (list
in this case) with NULL
values instead of - as I thought - values returned by names()
function. Why is that?
CodePudding user response:
The names are not passed to the function, only the values. If you want the names use names(vec). If you want to access both the names and the values use one of these:
# 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"