【问题标题】:appending tibbles using purrr::map使用 purrr::map 附加小标题
【发布时间】:2021-12-18 04:31:56
【问题描述】:

背景

我使用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

【问题讨论】:

    标签: r purrr furrr


    【解决方案1】:

    [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
    

    【讨论】:

      【解决方案2】:

      为什么不只是:

      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 
      

      【讨论】:

      • 我请求了一个采用 map2() 的解决方案,因为我正在运行的函数不是那么简单。
      猜你喜欢
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      相关资源
      最近更新 更多