【发布时间】: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 创建
【问题讨论】: