[英]Create a tibble row-wise using purrr
如何使用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])))
感謝和親切的問候
這是一個使用add_column
並將您的add_column
保持為列的想法,
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
列
與@ 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
這個解決方案有效,雖然我很確定,還有另一種方法來構建你的tibble,所以你不需要這個行創建:
map(vec,~rep(0,10)) %>% map(enframe) %>% map(spread,name,value) %>% bind_rows
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.