R - 如何从“扩散”矩阵中获取每列〜时间轴的系数?

问题描述 投票:0回答:2

我想收集每列~ind的线性回归系数。

这是我的数据:

temp <- data.frame(
  ind = c(1:10),
  `9891` = runif(10, 15, 75),
  `7891` = runif(10, 15, 75),
  `5891` = runif(10, 15, 75)
)

我试过了

result = data.frame()

cols <- colnames(temp)[-1]

for (code in cols) {
  fit <- lm(temp[, code] ~ temp$ind)
  coef <- coef(fit)['ind']
  result$ind <- code
  result$coef <- coef
}

但这不起作用。

任何人都可以修复我的方法,或提供更好的解决方案?另外,我想知道lapply()summarise_at()是否可以完成这项工作。

谢谢!

r loops linear-regression
2个回答
2
投票

这是一个summarise_at选项

temp %>%
    summarise_at(vars(-contains("ind")), list(coef = ~list(lm(. ~ ind)$coef))) %>%
    unnest()
#  X9891_coef X7891_coef X5891_coef
#1  25.927946 52.5668120  35.152330
#2   2.459137  0.3158741   1.013678

第一行给出偏移,第二行给出斜率系数。

或者仅提取斜率系数并将结果存储在长data.frame

temp %>%
    summarise_at(vars(-contains("ind")), list(coef = ~list(lm(. ~ ind)$coef[2]))) %>%
    unnest() %>%
    stack() %>%
    setNames(c("slope", "column"))
#        slope     column
#  1 2.4591375 X9891_coef
#  2 0.3158741 X7891_coef
#  3 1.0136783 X5891_coef

PS。在处理随机数据时,包含固定的随机种子以确保结果的可重复性始终是一种好习惯。


样本数据

set.seed(2018)
temp <- data.frame(
  ind = c(1:10),
  `9891` = runif(10, 15, 75),
  `7891` = runif(10, 15, 75),
  `5891` = runif(10, 15, 75)
)

2
投票

你可以使用sapply

sapply(temp[-1], function(x) coef(lm(x ~ temp$ind))[2])

#X9891.temp$ind X7891.temp$ind X5891.temp$ind 
#   -0.01252979    -2.94773367     2.57816244  

要获得最终的数据帧,您可以这样做

data.frame(ind = names(temp)[-1], 
 coef = sapply(temp[-1], function(x) coef(lm(x ~ temp$ind))[2]), row.names = NULL)

#      ind        coef
#1   X9891 -0.01252979
#2   X7891 -2.94773367
#3   X5891  2.57816244 

其中每一行代表列中的值。

数据

set.seed(1234)
temp <- data.frame(
   ind = c(1:10),
  `9891` = runif(10, 15, 75),
  `7891` = runif(10, 15, 75),
  `5891` = runif(10, 15, 75)
)
© www.soinside.com 2019 - 2024. All rights reserved.