anderlaini
anderlaini

Reputation: 1831

r - create function to calculate count of filtered rows in dataset

I'm trying to create a helper function that will calculate how many rows are there in a data.frame according parameters.

getTotalParkeds <- function(place, weekday, entry_hour){
  data <- PARKEDS[
                  PARKEDS$place      == place,
                  PARKEDS$weekday    == weekday,
                  PARKEDS$entry_hour == entry_hour
                  ]
  return(nrow(data))
}

Then I'm running this like:

getTotalParkeds('MyPlace', 'mon', 1)

So it is returning this error:

Warning: Error in : Length of logical index vector must be 1 or 11 (the number of columns), not 10000

I'm totally new to R, so I have no idea on what is happening.

Upvotes: 1

Views: 35

Answers (2)

beavis11111
beavis11111

Reputation: 574

Allowing different PARKEDS data, say next month's data:

getTotalParkeds <- function(input, place, weekday, entry_hour){

  row.count <- nrow(subset(input, place == place & 
                                  weekday == weekday & 
                                  entry_hour == entry_hour))
  return(row.count)
}

Upvotes: 0

Shree
Shree

Reputation: 11150

Here's the correction you need for your approach -

getTotalParkeds <- function(place, weekday, entry_hour){
  data <- PARKEDS[
                  PARKEDS$place      == place &
                  PARKEDS$weekday    == weekday &
                  PARKEDS$entry_hour == entry_hour,
                  ]
  return(nrow(data))
}

Upvotes: 2

Related Questions