1

I have a data frame with a column of year and quantity. Below is a sample data:

year <- c(1985, 1985, 1983, 1985, 1983)
quantity <- c(2,1,4,6,1)
mydata <- data.frame(year, quantity)

I want to extract a number of observations for each year. I have used the following code for a specific observation and it works fine. However in my original dataset I have 50 different years and I need something that works better than repeating this for every year:

newdata <- subset(mydata, year == 1985, select=c(quantity)) 
str(newdata)
codeforfun
  • 187
  • 10

2 Answers2

2

We can use table

table(mydata$year)

Or with count

library(dplyr)
mydata %>% 
    count(year)
akrun
  • 874,273
  • 37
  • 540
  • 662
1

Below another possible solution:

With useNA = 'always' you could detect possible NA values.

table(mydata$year, useNA = 'always') 
Earl Mascetti
  • 1,278
  • 3
  • 16
  • 31