簡體   English   中英

for循環在r中循環通過向量

[英]for loop in r -looping through vector

我試圖遍歷我的 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.

請問有什么建議嗎??

我們需要創建公式。 要么使用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(.)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM