alqacer
alqacer

Reputation: 57

how to get key after using map function in R

I'm trying to use map function in R and I have something like this

x <- list(a = 1, b = 2)
map(x, function (e) e + 100)

Is there a way to get the keys a, b inside the map function?

For example if I wanted to print

a 1
b 2

Upvotes: 1

Views: 163

Answers (1)

Waldi
Waldi

Reputation: 41220

As suggested by @akrun

x <- list(a = 1, b = 2))
l <- x %>% imap(~{list(.x,.y)}) 
do.call(rbind,l)

  [,1] [,2]
a 1    "a" 
b 2    "b" 

or even simpler:

do.call(rbind,x)
  [,1]
a    1
b    2

seems to answer exactly your expected output

Upvotes: 1

Related Questions