在进一步了解 tidyverse 后,我开始像 这篇文章中所描述的那样一次拟合多个线性模型。换句话说,我会按照以下方式进行操作:
library(dplyr)
library(tidyr)
library(purrr)
df <- data.frame(y = rnorm(10),
x1 = runif(10),
x2 = runif(10))
df %>%
gather(covariate, value, x1:x2) %>%
group_by(covariate) %>%
nest() %>%
mutate(model = map(.x = data , .f = ~lm(y ~ value, data = .))) %>%
mutate(rsquared = map_dbl(.x = model, .f = ~summary(.)$r.squared))
问题在于,当变量类型不同时,例如一个是数字,另一个是因子时,这种方法就会失败,因为
gather()
函数会将整个value
向量强制转换为因子。例如,df <- data.frame(y = rnorm(10),
x1 = runif(10),
x3 = sample(c("a", "b", "c"), 10, replace = TRUE))
df %>%
gather(covariate, value, x1:x3) %>%
sapply(class)
后面跟着警告信息
Warning message:
attributes are not identical across measure variables; they will be dropped
y covariate value
"numeric" "character" "character"
并且value
列是字符型的,所以使用nest()
的技巧将不再起作用,因为所有协变量都将被视为因子。
我想知道是否有一种整洁的方法来解决这个问题。