0

I want to make a table called Count_Table and in it, Id like to count the number of 0s, 1s, and 5s when column "num" == 1,2,3,4, etc.

For example, the code below will count the 0s,1s,and 5s in column "num" when "num == "1". This is great but i need to do this 34 more times since "num" goes from 1-35.

Count_Table <- table(SASS_data[num == "1"]$Visited5)

I am new to R and I don't know how to add 1 to the "num" and loop it until 35 so that the Count_Table includes the counts of 0,1,5 for all nums that exist (1-35). I am sorry if this is confusing and thank you for your help.

  • hi Callahan and welcome to the site. This is indeed confusing, could you post a sample of your data and your wanted output. It will make it a lot easier to help out :) – Jagge May 19 '21 at 14:54
  • [See here](https://stackoverflow.com/q/5963269/5325862) on making a reproducible example that is easier for folks to help with. That includes a sample of data, because right now it's unclear exactly what you're trying to do, but there are almost certainly questions already on SO that should help – camille May 19 '21 at 17:35
  • Also your description says you want to count frequencies of values in num based on num, but your code shows you counting frequencies of values in Visited based on num. I imagine what you actually want is the latter – camille May 19 '21 at 17:36

2 Answers2

0

lapply will generate a list of tables that span the columns of a dataframe. E.g.,

tablist <- lapply(mtcars, table)

If your dataframe contains columns you want to exclude, can do that by restricting the dataframe. E.g.,

tablist2 <- lapply(mtcars[, c(2, 4, 7)], table)
SteveM
  • 2,226
  • 3
  • 12
  • 16
0

Answer

Table works on multiple dimensions. Just put both num and Visited5 as arguments. This also works if not all unique values of Visited5 are present in every level of num, those cells will simply be set to 0.

Example

SASS_data <- data.frame(
  num = rep(1:5, each = 5),
  Visited5 = sample(1:3, 25, r = T)
)
table(SASS_data$num, SASS_data$Visited5)

#    1 2 3
#  1 2 1 2
#  2 1 3 1
#  3 1 1 3
#  4 2 0 3
#  5 2 2 1
slamballais
  • 3,161
  • 3
  • 18
  • 29