我有一個包含大量變數的資料集。在資料集中,我有一個預測變數和一個我想要調查的結果變數。我想找到對結果變數有顯著影響的協變數,或者預測變數和協變數對結果變數有顯著互動作用的協變數。
因此,如果能夠使用因變數上的所需預測變數依次回歸所有協變數,并創建一個關于協變數及其各自 p 值的效應和互動效應的表格,將會很方便。
我想做這樣的事情:
library(dplyr)
# Generating sample data
set.seed(5)
df <- data.frame(matrix(round(abs(2*rnorm(100*100)), digits = 0), ncol=100))
# Selecting covariates
covar <- names(df)[! names(df) %in% c("X1", "X2")]
# Running the lm function over the list of covariates. I should get the covariate coefficients from each regression, but I get an error when I try run this step.
coeff <- lapply(covar, function(x){
# Retrive coefficient matrix
summary(lm(X1 ~ X2 x X2*x, df))$coefficients %>%
# Coerce into dataframe and filter for covariates and interaction effects
as.data.frame(.) %>%
filter(row.names(.) %in% grep(x, rownames(.), value =
TRUE))}) %>%
# Finally I want to join all data frames into one
bind_rows(.)
我可以使用一些語法幫助。當我嘗試運行該函式時出現以下錯誤:
Error in h(simpleError(msg, call)): error in evaluating the argument 'object' in selecting a method for function 'summary': variable lengths differ (found for 'x')
uj5u.com熱心網友回復:
當您使用x(in lapply) inside 時function,最好使用pastefor 模型公式而不是僅僅指定它的公式。
lapply(covar, function(x){
modd <- paste0("X1 ~ X2 ", x, " X2 *", x)
summary(lm(modd, df))$coefficients %>%
as.data.frame(.) %>%
filter(row.names(.) %in% grep(x, rownames(.), value =
TRUE))}) %>%
bind_rows(.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/377757.html
上一篇:數字的R分類
