Performing lm() and segmented() on multiple columns in R

前端 未结 2 1201
[愿得一人]
[愿得一人] 2021-02-02 04:33

I am trying to perform lm() and segmented() in R using the same independent variable (x) and multiple dependent response variables (Curve1, Curve2, etc.) one by one. I wish to e

2条回答
  •  有刺的猬
    2021-02-02 05:13

    You can wrap the whole thing in a function, taking as the arguments the column name and the data, and use lapply on the column names, like this:

    library(segmented)
    run_mod <- function(varname, data){
    
      data$Y <- data[,varname]
      model <- lm(Y ~ x, data) # Linear model
      seg_model <- segmented(model, seg.Z = ~x) # Segmented model
      breakpoint <- as.matrix(seg_model$psi.history[[5]]) # Extract breakpoint
      coefficients <- as.matrix(seg_model$coefficients) # Extract coefficients
      summary_curve1 <- as.data.frame(rbind(breakpoint, coefficients)) 
      colnames(summary_curve1) <- varname
    
    return(summary_curve1)
    }
    
    
    lapply(names(dat)[2:ncol(dat)], function(x)run_mod(x, dat))
    

    Which gives the summary for each fitted curve (not sure which output you actually want).

提交回复
热议问题