Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why *apply returns named object instead of vector of values when using names() function?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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" 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading