R Is Not So Hard! A Tutorial, Part 16: Counting Values within Cases

by guest

by David Lillis, Ph.D.

SPSS has the Count Values within Cases option, but R does not have an equivalent function. Here are two functions that you might find helpful, each of which counts values within cases inside a rectangular array.

For example, you might have a data set consisting of responses to a questionnaire involving multiple Likert items scored 1 to 5. You may wish to know the number of items for which respondents selected a 5.

Note the syntax for creating a function, which I will not discuss here. Copy and paste the two functions into the R workspace. They both do the same job, so that you can choose either of them for your own data analysis.

countcases1 <- function(x, n) { apply(x, 1, function(r) sum(r == n)) } 


countcases2 <- function(x, n) { rowSums(x == n) }

Now let’s use these functions to count elements within a rectangular array. Let’s use the following array M.

M <- structure(c(1, 4, 5, 4, 5, 5, 3, 2, 5, 5, 5, 4, 5, 2, 5), .Dim = c(3L, 5L), .Dimnames = list(c("David", "Mary", "Anne"), NULL))

colnames(M) <- c("Item1", "Item2", "Item3", "Item4", "Item5")


       Item1  Item2 Item3 Item4 Item5
David     1     4     3     5     5
Mary      4     5     2     5     2
Anne      5     5     5     4     5

Let’s count the fives along the rows of M.

countcases1(M, 5)

 David  Mary  Anne
    2     2     4

Let’s use the other function to count the twos.

countcases2(M, 2)

David  Mary  Anne
    0     2     0

Each of the two functions has produced a vector of counts. Now let’s pick out the number of fives in the FIRST row using square brackets.

countcases1(M, 5)[1]



countcases1(M, 5)["David"]


To see the rest of the R is Not So Hard! tutorial series, visit our R Resource page.

About the Author: David Lillis has taught R to many researchers and statisticians. His company, Sigma Statistics and Research Limited, provides both on-line instruction and face-to-face workshops on R, and coding services in R. David holds a doctorate in applied statistics.

Bookmark and Share

Leave a Comment

Please note that, due to the large number of comments submitted, any comments on problems related to a personal study/project will not be answered. We suggest joining Statistically Speaking, where you have access to a private forum and more resources 24/7.

Previous post:

Next post: