3
votes

How can I create a tibble using purrr. These are my not working tries:

library(tidyverse)

vec <- set_names(1:4, letters[1:4])

map_dfr(vec, ~rep(0, 10)) # not working
bind_rows(map(vec, ~rep(0, 10))) # not working either

This would be my base R solution, but I would like to do it "tidy":

do.call(rbind, lapply(vec, function(x) rep(0, 10)))
#[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#a    0    0    0    0    0    0    0    0    0     0
#b    0    0    0    0    0    0    0    0    0     0
#c    0    0    0    0    0    0    0    0    0     0
#d    0    0    0    0    0    0    0    0    0     0

Please note that the rep-function is not the full function I will use. This would not be a preferred solution for my problem:

as_tibble(matrix(rep(0, 40), nrow = 4, dimnames = list(letters[1:4])))

Thx & kind regards

3
Rownames are very atypical for a tibble cause it indicates you are using wide, not long format. But you can generate your data separately, use bind_rows to generate a tibble and then set the rownames laterJulian_Hn
Losing the rownames would be ok for me. I am struggling most with binding the result vectors rowwise.r.user.05apr

3 Answers

3
votes

Here is an idea using add_column and keeping your rownames as a column,

library(tidyverse)

enframe(vec) %>% 
 add_column(!!!set_names(as.list(rep(0, 10)),paste0('column', seq(10))))

which gives,

# A tibble: 4 x 12
  name  value column1 column2 column3 column4 column5 column6 column7 column8 column9 column10
  <chr> <int>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>   <dbl>    <dbl>
1 a         1       0       0       0       0       0       0       0       0       0        0
2 b         2       0       0       0       0       0       0       0       0       0        0
3 c         3       0       0       0       0       0       0       0       0       0        0
4 d         4       0       0       0       0       0       0       0       0       0        0

You can easily drop value column If not needed

2
votes

Similar to @Sotos's solution, but using the new and shiny group_map function that comes with dplyr 0.8:

library(tidyverse)

enframe(vec) %>%
  group_by(name) %>%
  group_map(~rep(0,10) %>% as.list %>% bind_cols(.x, .))

Output:

# A tibble: 4 x 12
# Groups:   name [4]
  name  value    V1    V2    V3    V4    V5    V6    V7    V8    V9   V10
  <chr> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 a         1     0     0     0     0     0     0     0     0     0     0
2 b         2     0     0     0     0     0     0     0     0     0     0
3 c         3     0     0     0     0     0     0     0     0     0     0
4 d         4     0     0     0     0     0     0     0     0     0     0
1
votes

This solution works, although I'm pretty sure, that there is another way to structure your tibble so you don't need this rowwise creation:

map(vec,~rep(0,10)) %>% map(enframe) %>% map(spread,name,value) %>% bind_rows