Home > Software engineering >  Is there an easy way to get the frequencies column wise?
Is there an easy way to get the frequencies column wise?

Time:10-08

I have a list of Likert values, the values range from 1 to 5. Each possible response may occur once, more than once or not at all per column. I have several columns and rows, each row corresponds to a participant, each column to a question. There is no NA data.

Example:

c1 c2 c3
1 1 5
2 2 5
3 3 4
3 4 3
2 5 1
1 3 1
1 5 1

The goal is to count the frequencies of the answer options column wise, to consequently compare them.

So the resulting table should look like this:

- c1 c2 c3
1 3 1 3
2 2 1 0
3 2 2 1
4 0 1 1
5 0 2 2

I know how to do this for one column, and I can look at the frequencies with apply(ds, 1, table), but I do not manage to put this into a table to work further with.

Thanks!

CodePudding user response:

You may use table in sapply -

sapply(df, function(x) table(factor(x, 1:5)))

#  c1 c2 c3
#1  3  1  3
#2  2  1  0
#3  2  2  1
#4  0  1  1
#5  0  2  2

This approach can also be used in dplyr if you prefer that.

library(dplyr)
df %>% summarise(across(.fns = ~table(factor(., 1:5))))

CodePudding user response:

This should do it, using plyr:

count_df = setNames(data.frame(t(plyr::ldply(apply(df, 2, table), rbind)[2:6])), colnames(df))

count_df[is.na(count_df)] = 0

CodePudding user response:

We may use a vectorized option in base R

table(data.frame(v1 = unlist(df1), v2 = names(df1)[col(df1)]))
   v2
v1  c1 c2 c3
  1  3  1  3
  2  2  1  0
  3  2  2  1
  4  0  1  1
  5  0  2  2

data

df1 <- structure(list(c1 = c(1L, 2L, 3L, 3L, 2L, 1L, 1L), c2 = c(1L, 
2L, 3L, 4L, 5L, 3L, 5L), c3 = c(5L, 5L, 4L, 3L, 1L, 1L, 1L)),
 class = "data.frame", row.names = c(NA, 
-7L))
  • Related