Friday, February 12, 2016

Counting objects in a vector in R


There is an easy way to count the number of objects in a vector in R.... also known as getting your Freq on.

Suppose you create a vector called myVec with some elements in it, and you want to know the frequency (i.e., the count) of each object.

Simply convert it into a table, and then cast it as.data.frame.  The column names are the original vector name (myVec) and Freq.

       
> myVec <- c="" cat="" dog="" mouse=""> myDF <- as.data.frame="" myvec="" table=""> myDF
  myVec Freq
1   cat    3
2   dog    1
3 mouse    2
       
 

This also works if your vector is a column of a data frame as well.

The mysteries of the R programming language revealed.

Follow me on Twitter: @bioniclime