【问题标题】:Generating a new dataframe from an existing one using Purrr使用 Purrr 从现有数据框生成新数据框
【发布时间】:2020-09-07 20:41:09
【问题描述】:

我正在模拟一个数据集,需要根据我在单独的数据框中生成的汇总客户参数创建一系列虚假交易数据。我曾尝试使用lapply()map() 的变体来执行此操作,但我继续遇到错误。

我讨厌使用for() 循环。我该如何整理并以非常 R 的方式进行操作?

library(tidyverse)

customers <- letters[1:10]
trx <- 1 + rpois(n = 10, lambda = .4)

customer_df <- tibble(customer = customers,
                      transactions = trx)

# The function to create transactions based on the
# parameters provided in the customer_df

create_trx <- function(cid, trx) {

  customer <- rep(cid, trx)
  amount <- rnorm(trx, mean = 25, sd = 2)
  
  rtn_tbl <- tibble(customer = customer,
                    amount = amount)
  
  return(rtn_tbl)
}

# This is the ugly brute force way I can make it work. I'd like
# to use `map()` or a tidyier approach. The output of this
# function is a new dataframe z2. 

for (i in 1:nrow(customer_df)) {
  z <- create_trx(customer_df$customer[i], customer_df$transactions[i])
  if(exists("z2")) {
    z2 <- rbind(z2, z)
  } else {
    z2 <- z
  }
}

reprex package (v0.3.0) 于 2020-09-07 创建

【问题讨论】:

    标签: r tidyverse purrr


    【解决方案1】:

    也许,我们可以在用函数的参数名称或标识符设置列名之后使用pmap

    library(dplyr)
    library(purrr)
    customer_df %>% 
        set_names(c('cid', 'trx')) %>%
        pmap_dfr(create_trx)
    

    或者也可以通过匿名函数调用而不重命名列名来完成

    customer_df %>%
          pmap_dfr(~ create_trx(..1, ..2))
    

    【讨论】:

    • 这行得通!有很多的欣喜。谢谢。
    【解决方案2】:

    在基础 R 中,您可以使用 Map 为每一行应用 create_trx,这将返回可与 do.call + rbind 组合的数据帧列表。

    do.call(rbind ,Map(create_trx, customer_df$customer, customer_df$transactions))
    

    如果您对purrr/tidyverse 解决方案感兴趣,您可以使用map2_df,这将使上述解决方案更短。

    purrr::map2_df(customer_df$customer, customer_df$transactions, create_trx)
    
    # A tibble: 15 x 2
    #   customer amount
    #   <chr>     <dbl>
    # 1 a          22.4
    # 2 b          23.0
    # 3 b          24.3
    # 4 c          25.6
    # 5 c          26.5
    # 6 d          24.6
    # 7 e          27.4
    # 8 e          26.2
    # 9 e          24.3
    #10 f          24.3
    #11 f          27.3
    #12 g          21.3
    #13 h          23.8
    #14 i          26.2
    #15 j          23.4
    

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 2021-09-08
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      相关资源
      最近更新 更多