# 【R言語】mutateの中で動的変数を使用

```iris2 <- iris

for (n in 1:3) {
column_name = paste('column',n, sep = "")
iris2 = iris2 %>%
mutate(!!column_name := n)
}
```

# 【R言語】broomパッケージで複数モデルで線形回帰し、係数を可視化

R言語】broomパッケージで複数モデルで線形回帰し、係数を可視化

```library(tidyverse)
library(tidymodels)

df <- diamonds

df_input <- df %>%
mutate_if(is.ordered, factor, ordered = FALSE)
formulas = c(log(price) ~ clarity,
log(price) ~ clarity + carat,
log(price) ~ clarity + log(carat)) %>%
enframe("model_no", "formula")

#conf.int = TRUEで信頼区間を算出
df_result <- formulas %>%
mutate(model = map(formula, lm, data = df_input),
tidied = map(model, tidy,conf.int = TRUE),
glanced = map(model, glance))

#unnestでデータフレームに変換
df_coef <- df_result %>%
select(model_no, tidied) %>%
unnest() %>%
mutate_if(is.double, round, digits=2)

#係数を可視化する
df_coef %>%
filter(term != "(Intercept)") %>%
ggplot() +
geom_pointrange(aes(x = term, y = estimate, ymin = conf.low, ymax = conf.high,colour=as.factor(model_no)))+
coord_flip()

#横持に変換するとわかりやすい
#並び順を維持するためにfct_inorder()を使用（出てきた順に並ぶ）。
df_coef %>%
mutate(term = fct_inorder(term)) %>%
select(model_no,term,estimate) %>%
pivot_wider(names_from = model_no, values_from = estimate)
```