试图为R中的csv文件的每一行找到回归和p值

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

你好,我是R的新手,在尝试对每行进行线性回归时遇到了一些麻烦。

我无法附加实际的数据集,因为不允许共享它,但这是基本轮廓:

       Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec (...total 12 cols)              
Type 1
Type 2 
Type 3 
(... total 1680 rows)

The values are level of inventory for each type, numeric (no strings).

基本上我想做的是outlined here

((1)以时间为自变量的线性回归

((2)ANOVA测试以查看时间系数是否在统计上显着。

[我想做的是对每一行(即每种“类型”)进行回归分析,并以时间作为自变量,然后为每一行输出一个p值,该值将被添加到新列中的行中。目的是使用p值来查看每种类型的库存是否有趋势,而不必绘制1680种不同类型的产品的图,因为这很难分析。

我已经针对每行使用lm()浏览了许多类似的问题,但没有一个问题涉及到如何输出p值而不是系数本身。希望有人可以帮助!

r linear-regression anova
1个回答
0
投票

这些注释很有用,即,在模型有效性方面,请参阅交叉验证。这是我要使用data.table程序包处理代码的方式:

# some fake value
input <- data.frame(type=1:3, x1=rnorm(3), x2=rnorm(3), x3=rnorm(3), x4=rnorm(3))

# package for data manipulating, run install.packages("data.table")
library(data.table)

# convert to data.table and set names based on time index
input_dt <- as.data.table(input)
setnames(input_dt, c("type", 1:(ncol(input_dt)-1)))
input_dt[]

# wide to long format for modelling
dt <- melt(input_dt, id.vars = "type", variable.name="time")
dt[, time := as.numeric(time)]

# function to fit lm and get p-value
# replace with yours
myPvalFun <- function(data){

  # model. Do value ~ -1 + time for no intercept model
  mod <- lm(value ~ time, data=data)

  # p-values for regressor
  pvals <- summary(mod)$coefficients[,4]

  # just time p-value, [1] is intercept
  return(pvals[2])
}

# loop across using lapply and splitting the data up
pvals_list <- lapply(unique(dt$type), function(i){
  mod_dt <- dt[type==i,]
  data.table(type=i, pval=myPvalFun(mod_dt))
})
# bind list to a data.table
pvals <- rbindlist(pvals_list)

# make output and convert to data.frame
output_dt <- merge(input_dt, pvals, by="type")
output <- as.data.frame(output_dt)
© www.soinside.com 2019 - 2024. All rights reserved.