Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a tibble row-wise using purrr

Tags:

r

purrr

tidyverse

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

like image 905
r.user.05apr Avatar asked May 23 '26 02:05

r.user.05apr


1 Answers

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

like image 190
Sotos Avatar answered May 26 '26 11:05

Sotos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!