我試圖遍歷我的 df 中的所有 cols 并對每個 cols 運行一個 prop 測驗。
library(gss)
只運行一個我可以使用的變數——
infer::prop_test(gss,
college ~ sex,
order = c("female", "male"))
但是現在我想像這樣為我的 df 中的每個變數運行它:
cols <- gss %>% select(-sex) %>% names(.)
for (i in cols){
# print(i)
prop_test(gss,
i~sex)
}
但是這個回圈不能識別 i;
Error: The response variable `i` cannot be found in this dataframe.
請問有什么建議嗎??
uj5u.com熱心網友回復:
我們需要創建公式。要么使用reformulate
library(gss)
library(infer)
out <- vector('list', length(cols))
names(out) <- cols
for(i in cols) {
out[[i]] <- prop_test(gss, reformulate("sex", response = i))
}
-輸出
> out
$college
# A tibble: 1 × 6
statistic chisq_df p_value alternative lower_ci upper_ci
<dbl> <dbl> <dbl> <chr> <dbl> <dbl>
1 0.0000204 1 0.996 two.sided -0.0917 0.101
$partyid
# A tibble: 1 × 3
statistic chisq_df p_value
<dbl> <dbl> <dbl>
1 12.9 3 0.00484
$class
# A tibble: 1 × 3
statistic chisq_df p_value
<dbl> <dbl> <dbl>
1 2.54 3 0.467
$finrela
# A tibble: 1 × 3
statistic chisq_df p_value
<dbl> <dbl> <dbl>
1 9.11 5 0.105
或者 paste
for(i in cols) {
prop_test(gss, as.formula(paste0(i, " ~ sex")))
}
資料
library(dplyr)
data(gss)
cols <- gss %>%
select(where(is.factor), -sex, -income) %>%
names(.)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/313521.html
上一篇:R如何找到具有特定值的最近行
下一篇:如何在for回圈中洗掉串列的元素
