使用 purrr::map 在数据框中的列上迭代线性模型 [英] Using purrr::map to iterate linear model over columns in data frame

查看:59
本文介绍了使用 purrr::map 在数据框中的列上迭代线性模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试做一个练习,以更加熟悉如何使用 purrr 中的地图功能.我正在创建一些随机数据(10 个数据点的 10 列),然后我想使用 map 对数据框中的结果列执行一系列回归(即 lm(y ~ x, data = )).

I am trying to do an exercise to become more familiar with how to use the map function in purrr. I am creating some random data (10 columns of 10 datapoints) and then I wanted to use map to perform a series of regressions (i.e. lm(y ~ x, data = )) over the resulting columns in the data frame.

如果我只是重复使用第一列作为y",我想对从 1 到 10 的每一列作为x"执行 10 次回归.显然结果并不重要——这只是方法.我想最终得到一个包含 10 个线性模型对象的列表.

If I just repeatedly use the first column as 'y', I want to perform 10 regressions with each column from 1 to 10 as 'x'. Obviously the results are unimportant - it's just the method. I want to end up with a list of 10 linear model objects.

list_of_vecs <- list()
for (i in 1:10){ 
 list_of_vecs[[paste('vec_', i, sep = '')]] <- rnorm(10,0,1)
}
df_of_vecs <- as.data.frame(list_of_vecs)

在这里,我卡住了:

map(df_of_vecs, ~ lm(df_of_vecs[[1]] ~ . ?)

任何提示将不胜感激.

谢谢.

推荐答案

您需要根据列名构造公式,然后映射 lm 作为最后一步.你可以用两个 map 来做到这一点:

You need to construct the formulas from the column names, and then map lm as the last step. You can do this with two maps:

library(purrr)

df_of_vecs %>% 
    names() %>% 
    paste('vec_1 ~', .) %>% 
    map(as.formula) %>% 
    map(lm, data = df_of_vecs)

或一个:

df_of_vecs %>% 
    names() %>% 
    paste('vec_1 ~', .) %>% 
    map(~lm(as.formula(.x), data = df_of_vecs))

两者都返回相同的十个模型列表.

Both return the same list of ten models.

这篇关于使用 purrr::map 在数据框中的列上迭代线性模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆