Reputation: 111
In this data frame, I'm trying to find the number of right handed batters in the <5 years group without simply counting it manually. Here's a sample of the data:
Status Handed
<5 yrs Right
<5 yrs Right
<5 yrs Left
How to I use an R function to do that instead of counting it out?
Upvotes: 0
Views: 56
Reputation: 427
**length(df[df$Status=='<5 yrs' & df$Handed == 'Right',])**
here df is name of the data frame you are using. This works
Or use sqldf package.
**install.packages("sqldf")
**library("sqldf")**
**df$Count=1**
**sqldf("select sum(Count) from df where Status='<5 yrs' and
Handed='Right')****
Upvotes: 0
Reputation: 145755
The standard solution to count something is sum
. In this case,
sum(df$Handed[df$Status == "<5 yrs"] == "Right")
For counting the number of times a condition occurs, sum
should be your go-to.
table
, as demo'd in Yannis's answer is useful if you want counts of all possibilities, e.g., table(df$Handed[df$Status == "<5 yrs"])
gives the counts of Left and Right (and anything else in the handed column, and it is also do crosstabulations, e.g., with(df, table(Handed, Status))
will give counts of handedness for each of the status categories.
Upvotes: 0
Reputation: 1709
You could try:
table(df$Handed[df$Status == "<5 yrs"])
Or if you want the full breakdown based on Status category, you just do:
table(df$Handed, df$Status)
Upvotes: 1