使用purrr创建一个逐行的tibble

问题描述 投票:3回答:3

如何使用purrr创建一个tibble。这些是我不工作的尝试:

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

这将是我的基础R解决方案,但我想这样做“整洁”:

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

请注意,rep-function不是我将使用的全部功能。这不是我的问题的首选解决方案:

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

感谢和亲切的问候

r tidyverse purrr
3个回答
3
投票

这是一个使用add_column并将你的rownames保持为列的想法,

library(tidyverse)

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

这使,

# 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

你可以轻松地删除value列如果不需要


2
投票

与@ Sotos的解决方案类似,但使用dplyr 0.8附带的新的闪亮group_map功能:

library(tidyverse)

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

输出:

# 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
投票

这个解决方案有效,虽然我很确定,还有另一种方法来构建你的tibble,所以你不需要这个行创建:

map(vec,~rep(0,10)) %>% map(enframe) %>% map(spread,name,value) %>% bind_rows
© www.soinside.com 2019 - 2024. All rights reserved.