我想在按因子拆分的資料幀串列中使用解釋變數回圈lm()變數(回應)模型。i最后,我想創建兩個將顯示lm系數的資料框:第一個將顯示在模型中測驗slope 的p.value回應變數作為列和行中的因子水平。
我設法運行并列印模型的輸出summary,lm但不確定如何創建適當的slope資料p.value框。
這是我所做的:
data (iris)
iris_split = split (iris,f=iris$Species) ### Split the data by factor "Species"
我想為以下每個變數運行 lm 模型(為了問題而被視為回應)Petal.Width
vars = as.vector (unique (colnames (subset (iris, select = -c(Species, Petal.Width )))))
#Output:
#> vars
#[1] "Sepal.Length" "Sepal.Width" "Petal.Length"
iris_lm = for (i in vars) { # loop across vars
lm_summary = lapply (iris_split, FUN = function(x)
summary(lm (x[,i] ~ x[,"Petal.Width"]))) #Where (x) is levels of factors "Species"
print(i) # so I could see which variable is tested in the model
print(lm_summary)
}
如何創建slop.dfand p.val.df?他們需要看起來像這樣:
#> slop.df
# Species Sepal.Length Sepal.Width Petal.Length
#1 setosa slope? slope? slope?
#2 versicolor slope? slope? slope?
#3 virginica slope? slope? slope?
需要顯示實際斜率而不是"slope?"占位符,同樣適用p.val.df
uj5u.com熱心網友回復:
[tidyverse][1] 中的軟體包使這相當方便:
iris %>%
pivot_longer(-c(Species, Petal.Width),
names_to = 'variable',
values_to = 'value'
) %>%
group_by(Species, variable) %>%
## mind to return the model results as a list!
summarise(model_summary = list(summary(lm(Petal.Width ~ value)))) %>%
rowwise %>%
mutate(slope = model_summary$coefficients[2, 'Estimate'],
## p = model_summary$coefficients[2, 'Pr(>|t|)']
) %>%
ungroup %>%
pivot_wider(id_cols = Species,
names_from = 'variable',
values_from = 'slope')
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/454303.html
