Home > Blockchain >  crosstab function behaves differently inside loop than outside
crosstab function behaves differently inside loop than outside

Time:09-27

I am trying to use a loop to run crosstabs. The crosstab function (from the pollster package) behaves differently in the loop than outside of it. I will use the illinois dataset in the pollster package for my example here.

If I run it outside the loop

library(pollster)

xtab2 <- illinois |> 
  crosstab(educ6, maritalstatus, weight = weight)

xtab2

I get a table

educ6 Married Widow/divorced Never married n
LT 40.01702 29.05581 30.92717 10770999
HS 52.87883 20.98206 26.13911 31409418
Some Col 44.56356 17.42161 38.01483 21745113
AA 57.40460 18.37234 24.22307 8249909
BA 61.14996 11.29282 27.55722 19937965
Post-BA 70.65086 12.86814 16.48100 10565110

But if I run:

loop_vars <- c("maritalstatus")

for(i in loop_vars){ 
  
xtab2 <- illinois |>
  crosstab(educ6, i, weight = weight)
}

xtab2

The the table looks like:

educ6 maritalstatus n
LT 100 10770999
HS 100 31409418
Some Col 100 21745113
AA 100 8249909
BA 100 19937965
Post-BA 100 19937965

Why is R reading the exact same code differently when it's in a loop?

CodePudding user response:

In case anyone runs across a similar problem, doing this solved it

loop_vars <- c("maritalstatus")

for(i in loop_vars){ 
  
  var <- i
  
xtab2 <- illinois |>
  crosstab(educ6, !!ensym(var), weight = weight)
}

xtab2
  • Related