1

背景

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

代表

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
4

2 回答 2

2

分配[i]似乎是一个错字

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

除此之外,如果我们需要折叠行,请使用_dfr后缀map

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
于 2021-11-03T19:47:08.450 回答
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 
于 2021-11-03T19:52:37.890 回答