Thursday, February 17, 2011

using sum() like excel's "countif()"

sum()

#In excel there's a command "count if" that lets you count the number of items that #equals a certain value, like "COUNT it IF it equals X"

#There isn't an actual countif command in R as far as I know, but the exact same thing #can be done with the sum() command by including a logical operator(eg ==, >, >=) #within the command

#For example, let's say there is a vector "Year_2004" that has codes what what #reproductive stage an animal is in.

Year_2004<-c(2,1,1,2,1,2,1,2,2,2,2,2,2,2,2,2,3,2,2,2,3,3,3,3,3,3,3,3,3,4,2,2,2,5,2)

#You can quickly count the number of 2s in the vector like this

total_2 <- sum(Year_2004 == 2)

#The data in the column "Year_2004" that equals 2 will be counte up and saved to the #object "total_2"

#output =
#[1] 19

#If the "== 2" was not included, it would actually sum up all the elements of Year_2004

total_2 <- sum(Year_2004)

#output
#[1] 81

#The help file states it this way:

help(sum)
#"Logical true values are regarded as one, false values as zero."

No comments:

Post a Comment