【发布时间】:2018-11-07 15:38:01
【问题描述】:
我一直在为聚类生成一些特征,并且需要基于随时间提交的客户索赔的相关系数。我使用此代码通过在嵌套的数据块上运行 lm 模型来获取系数:
provProfileTemp <- byProvProfile %>%
mutate(date = ymd(paste(Year, Month, "01", sep = "-"))) %>%
select(-Month, -Year) %>%
group_by(AccountNumber, date) %>%
count() %>%
group_by(AccountNumber) %>%
mutate(total_claims = sum(n)) %>%
ungroup() %>%
mutate(numeric_date = as.numeric(date)/(24*60*60)) %>% # POSIX conversion for summary(lm)
select(AccountNumber, numeric_date, claims = n, total_claims) %>%
nest(-AccountNumber, -total_claims)
coeffs <- provProfileTemp %>%
mutate(
fit = map(provProfileTemp$data, ~lm(numeric_date ~ claims, data = .)),
results = map(fit, summary, correlation = TRUE),
coeff = results %>% map(c("correlation")) %>% map(3)
) %>%
select(AccountNumber, coeff, total_claims)
顶部块创建回归线所需的变量,并将数据嵌套到包含帐号、总索赔和回归数据的小标题的小标题中。在第二个块中使用purrr::map,我可以拟合一条线,从摘要中获取结果,并从摘要中提取系数。
结果正确且工作正常,但是,新列是一个列表,其中包含单个系数值。我无法压缩列表以将新列用作系数而不是列表。使用unlist() 会出现此错误:Error in mutate_impl(.data, dots) : Columncoeffmust be length 27768 (the number of rows) or one, not 21949。这是因为unlist() 没有返回相同数量的元素。我使用purrr::flatten 或unlist(lapply(coeff, "[[", 1)) 等函数得到了类似的结果。
关于如何将列表正确展平为单个值或以不需要生成这样的系数的不同方式解决问题的任何建议?任何帮助是极大的赞赏。谢谢你。
这是数据的样子:
AccountNumber coeff total_claims
<int> <list> <int>
16 <dbl [1]> 494
19 <dbl [1]> 184
45 <dbl [1]> 81...
这里是虚拟数据:
provProfileTemp <- structure(list(AccountNumber = c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L
), Year = c(2018L, 2017L, 2018L, 2018L, 2018L, 2017L, 2018L,
2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L, 2018L,
2018L, 2018L, 2018L, 2018L), Month = c(4L, 11L, 1L, 1L, 3L, 10L,
1L, 3L, 7L, 1L, 5L, 10L, 5L, 2L, 4L, 4L, 4L, 3L, 2L, 1L)), .Names = c("AccountNumber",
"Year", "Month"), row.names = c(NA, -20L), class = c("tbl_df",
"tbl", "data.frame"))
【问题讨论】:
-
我想你可能想要
map_dbl(3)而不是map(3)。如果您输入reproducible example,我将能够验证。 -
我正在制作一个虚拟数据框,但是,我似乎无法强制 R 将该列设为列表。我之前使用过
map_dbl,但它并没有像我期望的那样工作。我得到Error in mutate_impl(.data, dots) : Evaluation error: Result 20 is not a length 1 atomic vector -
绝对需要一个示例数据集。你可以
dput()的一部分provProfileTemp并将其添加到问题中吗?当我使用mtcars进行分组回归时,map_dbl()似乎工作正常:mtcars %>% group_by(cyl) %>% nest() %>% mutate(fit = map(data, ~ lm(mpg ~ wt, data = .x)), results = map(fit, summary, correlation = TRUE), coef = results %>% map(c("correlation")) %>% map_dbl(3)) -
最后有没有试过
unnest(coeff)? -
根据我得到的错误,
unneston coeff 不适用于列表。