0

I need to tabulate many categorical variables. I am using the function freq from questionr library to do it. My data frame is called esp.

I create an object with the categorical variables as following:

symp <- c("asthma", "flu", "cough", "sivilance", "fever")

I used the library foreach to tabulte all variables in symp:

library(foreach)

foreach(esp[symp]) %do% questionr::freq(i, cum = TRUE, total = TRUE, na.last = T)

However, it did not work, the result was the following:

[[1]]
      n   % val% %cum val%cum
3     1 100  100  100     100
Total 1 100  100  100     100

[[2]]
      n   % val% %cum val%cum
3     1 100  100  100     100
Total 1 100  100  100     100

[[3]]
      n   % val% %cum val%cum
3     1 100  100  100     100
Total 1 100  100  100     100

[[4]]
      n   % val% %cum val%cum
3     1 100  100  100     100
Total 1 100  100  100     100

[[5]]
      n   % val% %cum val%cum
3     1 100  100  100     100
Total 1 100  100  100     100

I need a table for each variable.

How can I tabulate all the variables without repeating the code?

Thanks

DavidMB
  • 7
  • 3
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. Include an example `esp` in the question. – MrFlick Aug 23 '23 at 15:46

1 Answers1

1

When using foreach, make sure to define your iteration variable. I get an error when running your code that says "object 'i' not found". The name i isn't special. It's just used in many of the examples. Here's how it looks with a different name

foreach(col=esp[symp]) %do% questionr::freq(col, cum=TRUE, total=TRUE, na.last=T)

What ever you name the values when you call foreach() is what the variable name will be in the block. Here I used col rather than i.

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • I really appreciate your help. Now I understand how to use `foreach`. The code works perfectly. – DavidMB Aug 23 '23 at 19:06