sapply function code no longer working

While this code was working before, it is no longer working now - and comes up with this error (below the code). Any tips for troubleshooting it?

# regression
my_lms <- sapply(1:ncol(df), function(x) lm(df[,x] ~ df[,1])) # run linear regression models across all vars in df and store in my_lms
tmp <- sapply(my_lms, coef)

ERROR: Error in object$coefficients : $ operator is invalid for atomic vectors

this is my_lms:

is a screenshot, not an R object that can be reproduced. Lacking a reprex. See the FAQ, I made up some data and guessed that the first sapply worked and the second was not.

get_coef <- function(x) lm(x ~ mpg, data = mtcars) |> coef()
apply(mtcars[2:11],2,get_coef)
#>                   cyl      disp         hp       drat        wt       qsec
#> (Intercept) 11.260683 580.88382 324.082314 2.38248715  6.047255 15.3547689
#> mpg         -0.252515 -17.42912  -8.829731 0.06042994 -0.140862  0.1241366
#>                      vs          am       gear       carb
#> (Intercept) -0.67816541 -0.59149275 2.50626625  5.7787984
#> mpg          0.05553164  0.04966211 0.05879527 -0.1476459

Created on 2023-02-28 with reprex v2.0.2

1 Like

simply change your fist sapply to lapply to be guaranteed a list result. (because sapply chose to give you a matrix/array)

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.