使用 purrr::map 添加 tibbles

appending tibbles using purrr::map

背景

我使用 map2 编写了一个函数,旨在生成数据帧或数据帧列表。我的问题是此函数生成未分配给 object 的单个表。我想要的输出是一个数据框,它存储矢量化循环每次迭代的输出小标题。

代表

df_coefs <- list()

df <- 
  tibble(names = c("john", "charlie", "lucy"), colours = c("green", "grey", "silver"))


funx <- function(name, colour) {
  
  coef <- runif(1, 0, 30)
  
  df_coefs[[i]] <- 
      tibble_row(names = name, 
                 colours = colour,
                 coefs = coef)
}

map2(.x = df$names,
     .y = df$colours,
     .f = funx)

当前输出

[[1]]
# A tibble: 1 × 3
  names colours coefs
  <chr> <chr>   <dbl>
1 john  green    11.1

[[2]]
# A tibble: 1 × 3
  names   colours coefs
  <chr>   <chr>   <dbl>
1 charlie grey     3.73

[[3]]
# A tibble: 1 × 3
  names colours coefs
  <chr> <chr>   <dbl>
1 lucy  silver   29.4

期望的输出

  names colours coefs
  <chr> <chr>   <dbl>
1 john  green    11.1
2 charlie grey   3.73
3 lucy  silver   29.4

[i] 的作业似乎有错字

funx <- function(name, colour) {
  
  coef <- runif(1, 0, 30)
  
  
      tibble_row(names = name, 
                 colours = colour,
                 coefs = coef)
                 
}

除此之外,如果我们需要折叠行,请在 map

中使用后缀 _dfr
library(purrr)
map2_dfr(.x = df$names,
      .y = df$colours,
      .f = funx)
# A tibble: 3 × 3
  names   colours coefs
  <chr>   <chr>   <dbl>
1 john    green    14.3
2 charlie grey     25.8
3 lucy    silver   13.1

为什么不只是:

df <- tibble(
    names = c("john", "charlie", "lucy"), 
    colours = c("green", "grey", "silver"),
    coef = runif(3, 0, 30)
)
df
# A tibble: 3 x 3
  names   colours  coef
  <chr>   <chr>   <dbl>
1 john    green    4.37
2 charlie grey    17.8 
3 lucy    silver  19.1