我在使用purrr::map()
和mutate(across(...))
时遇到了困难。
我想要进行线性模型,并从单个列中预测出多个列的斜率估计值。
以下是我在示例数据集中尝试的内容:
mtcars %>%
mutate(across(-mpg),
map(.x, lst(slope = ~lm(.x ~ mpg, data = .x) %>%
tidy() %>%
filter(term != "(Intercept") %>%
pull(estimate)
)))
我需要的输出是针对每个非 mpg 列都添加了 _slope 后缀的新列,例如cyl_slope。
在我的实际数据中,我还会按另一个变量进行分组,以便为每个预测变量的每个组计算斜率。我已经可以使用标准的 mutate 函数来针对每个变量单独完成此操作,如下所示:
df %>%
group_by(unitid) %>%
nest() %>%
mutate(tuition_and_fees_as_pct_total_rev_slope = map_dbl(data, ~lm(tuition_and_fees_as_pct_total_rev ~ year, data = .x) %>%
tidy() %>%
filter(term == "year") %>%
pull(estimate)
))
因此:
- 我认为我的问题是如何将要预测的列名传递给
lm
。 - 我不知道解决方案是否需要嵌套,所以如果在考虑的
mtcars
示例中,可以给予一些提示就好了。
across(-mpg)
已关闭,2)data = .x
应该是原始数据,因为.x
是一个向量。 - akrun