Get Number of Non-NA Values by Group in R (Example Code)

In this R programming tutorial you’ll learn how to get the number of non-NA values by group.

Construction of Example Data

data(iris)                           # Preparing the example data
iris_NA <- iris[c(1:4, 51:53, 101:105), c(3, 5)]
iris_NA$Petal.Length[c(1, 2, 4, 5, 7, 9)] <- NA
iris_NA
#     Petal.Length    Species
# 1             NA     setosa
# 2             NA     setosa
# 3            1.3     setosa
# 4             NA     setosa
# 51            NA versicolor
# 52           4.5 versicolor
# 53            NA versicolor
# 101          6.0  virginica
# 102           NA  virginica
# 103          5.9  virginica
# 104          5.6  virginica
# 105          5.8  virginica

Example: Counting the non-NA Values by Group Using the aggregate Function

aggregate(Petal.Length ~ Species,    # Printing the number of non-NAs by group
          data = iris_NA,
          function(x) {sum(!is.na(x))},
          na.action = NULL)
#      Species Petal.Length
# 1     setosa            1
# 2 versicolor            1
# 3  virginica            4

Related Articles

You may find some related R programming language tutorials on topics such as groups, numeric values, graphics in R, and ggplot2 below.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top