【发布时间】:2018-08-20 18:59:00
【问题描述】:
我想将 (mutate) 多列附加到数据框中,这些列存储在矩阵中。有没有办法使用 tidyverse 中的函数来做到这一点? (请注意,虽然可以使用 base:: 函数。)同样,我要问的是使用 tidyverse 中的函数最自然(或惯用)的方法是什么。
例如,假设我们估计一个分位数回归:
library(dplyr)
tibble(x = runif(100)) %>%
mutate(y = rnorm(n())) ->
EstimationData
library(quantreg)
taus <- (1:9)/10
rq_fit <- rq(y ~ x, tau = taus, data = EstimationData)
我们想根据x 的以下值来预测模型:
PredictionData <- tibble(x = seq(0, 1, len = 10))
这可以通过以下方式完成:
predict(rq_fit, newdata = PredictionData)
返回一个矩阵(每个tau对应一列)。很自然的事情是将预测与其对应的xs 打包在一起。人们可能希望能够将上述矩阵mutate() 转换为PredictionData,但据我所知,这是不可能的。一种可能性是:
PredictionData %>%
data.frame(predict(rq_fit, newdata = .), check.names = FALSE) # (*)
虽然它依赖于base::data.frame(),但效果很好(特别是因为矩阵列有名称)。请注意,tibble() 和 as_tibble() 不起作用。
尝试编写更惯用的 tidyverse 代码的一种方法是将矩阵转换为向量列表,如下所示:
row_split <- function(X) split(X, row(X, as.factor = TRUE))
PredictionData %>%
mutate(y = row_split(predict(rq_fit, newdata = .))) %>%
unnest(.id = 'tau_ix') %>%
mutate(tau = taus[as.integer(tau_ix)]) %>%
select(-tau_ix)
但我不相信它会更好。
方法(*)是最好的方法吗?
【问题讨论】: