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


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)) } 

OR

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")

M

       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]

David
    2

OR:

countcases1(M, 5)["David"]

David
    2

That wasn’t so hard! In our next blog post we will learn about using R to test for the existence of a particular value.

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.

See our full R Tutorial Series and other blog posts regarding R programming.

 

Getting Started with R
Kim discusses the use of R statistical software for data manipulation, calculation, and graphical display.

Reader Interactions


Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that, due to the large number of comments submitted, any questions 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.