spore234
spore234

Reputation: 3640

second argument in map function

I have a tibble like this:

uuu <- structure(list(Id = c("a", "b"),
                      lists = list(c(1:2), c(100:103))
),
.Names = c("Id", "lists"),
row.names = c(NA, 2L), class = c("tbl_df", "tbl", "data.frame"))

> uuu
# A tibble: 2 x 2
  Id    lists    
* <chr> <list>   
1 a     <int [2]>
2 b     <int [4]>

In this example it has 2 rows and 2 columns, the first column is a character column called id and the second column is called lists and contains lists of integers.

Now I want to map a function over the list elements, for example the sqrt function:

res <- uuu %>% mutate(res = map(lists, sqrt))

> res
# A tibble: 2 x 3
  Id    lists     res      
  <chr> <list>    <list>   
1 a     <int [2]> <dbl [2]>
2 b     <int [4]> <dbl [4]>

res now has a new column with all the results of the sqrt function.

Now I want to unlist the results in the res column, but I also want to have a new column that indicates from which id the result is from.

I can unlist the results like this:

> unlist(res$res)
[1]  1.000000  1.414214 10.000000 10.049876 10.099505 10.148892

but what I actually want is something like this (here done manually for illustration):

res2 <- data.frame(res = unlist(res$res),
            ids = c(rep("a", 2), rep("b", 4)))

> res2
        res ids
1  1.000000   a
2  1.414214   a
3 10.000000   b
4 10.049876   b
5 10.099505   b
6 10.148892   b

Ideally, I would want to pass this directly in the mapping part if possible, for cases where I define my own function, like this:

res <- uuu %>% mutate(res = map(lists, my_sqrt, id = id))

where my_sqrt is like this:

my_sqrt <- function(x, id) return(sqrt(x), id)

Upvotes: 1

Views: 156

Answers (1)

akrun
akrun

Reputation: 886938

We can use unnest

library(tidyverse)
res %>% 
  select(-lists) %>%
  unnest

Upvotes: 1

Related Questions