Changing and assigning new variable names with purrr::map()

倾然丶 夕夏残阳落幕 提交于 2021-02-10 05:03:10

问题


I am just starting to get the hang of writing functions and using lapply / purrr::map() to make my code more concise, but clearly have not understood it completely yet. In my current example, I want to rename coefficient names of lm_robust objects and then change the lm_robust object to incorporate the new names. I currently do this:

library(dplyr)
library(purrr)
library(estimatr)

df <- tibble(interest = rnorm(1000), maturity = runif(1000, 1, 12), genderfemale = rbernoulli(1000),
            y = 0.5*interest + 2*maturity - 3*genderfemale + rnorm(1000, sd = 0.25))

model1 <- lm_robust(y ~ interest + maturity + genderfemale, data = df, se_type = "stata")
model2 <- lm_robust(y ~ interest + I(interest^2) + maturity + genderfemale, data = df, se_type = "stata")

rename_coefficients <- function(x) {
  x$term[which(x$term == "interest")] <- "Interest Rate"
  x$term[which(x$term == "I(interest^2)")] <- "Interest Squared"
  x$term[which(x$term == "maturity")] <- "Loan Maturity"
  x$term[which(x$term == "genderfemaleTRUE")] <- "Female Borrower"

  return(x$term)
}

temp <- map(list(model1, model2), rename_coefficients)
model1$term <- temp[[1]]
model2$term <- temp[[2]]

This works, but in my use-case I have many more models and it bothers me to first assign the result of the map() to temp and then include the part model1$term <- temp[[1]] for each model.

There must be a more efficient way to do this?


回答1:


We can combine the two steps by doing

purrr::map(list(model1, model2), ~{.x$term <- rename_coefficients(.x);.x})

#[[1]]
#                Estimate Std. Error   t value Pr(>|t|) CI Lower CI Upper  DF
#(Intercept)     -0.01957   0.020690   -0.9457   0.3445 -0.06017  0.02104 996
#Interest Rate    0.50310   0.008145   61.7719   0.0000  0.48712  0.51909 996
#Loan Maturity    2.00225   0.002563  781.3051   0.0000  1.99722  2.00728 996
#Female Borrower -2.97232   0.015790 -188.2375   0.0000 -3.00331 -2.94134 996

#[[2]]
#                  Estimate Std. Error   t value Pr(>|t|) CI Lower  CI Upper  DF
#(Intercept)      -0.016819   0.021597   -0.7787   0.4363 -0.05920  0.025563 995
#Interest Rate     0.502921   0.008105   62.0532   0.0000  0.48702  0.518825 995
#Interest Squared -0.002588   0.005618   -0.4606   0.6452 -0.01361  0.008436 995
#Loan Maturity     2.002219   0.002568  779.8058   0.0000  1.99718  2.007257 995
#Female Borrower  -2.972270   0.015799 -188.1354   0.0000 -3.00327 -2.941268 995

This would return you a list of models backs with term changed.


Or same using lapply

lapply(list(model1, model2), function(x) {x$term <- rename_coefficients(x);x})


来源:https://stackoverflow.com/questions/57425613/changing-and-assigning-new-variable-names-with-purrrmap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!