Home > Blockchain >  Filtering vector by values with filter()
Filtering vector by values with filter()

Time:05-06

I'm filtering my experiment data, I want to get all the rows were the time is between 180 - 1800 seconds.

I use filter() like this:

dat = dat %>%
  filter(Duration..in.seconds. > 180) %>%
  filter(Duration..in.seconds.  < 1800) 

The first filter works well, but the second one filters all the data, which is wrong, here is the vector :

dat$Duration..in.seconds.
[1] "114"  "188"  "453"  "114"  "188"  "453"  "114"  "188"  "453"  "188"  "453"  "2000"
[13] "2000" "1900" 

as you see, the second filter is suppose to filter only 2 rows. Can you spot the problem?

CodePudding user response:

I assume that your data is in characters, so to filter that you first have to convert that to numeric. After that you can filter the conditions using one filter function with & operation. You can use the following code:

dat <- data.frame(Duration..in.seconds. = c("114",  "188",  "453",  "114" , "188" , "453" , "114" , "188" , "453" , "188" , "453",  "2000" ,"2000" ,"1900" ))

library(dplyr)

dat = dat %>%
  mutate(Duration..in.seconds. = as.numeric(Duration..in.seconds.)) %>%
  filter(Duration..in.seconds. > 180 & Duration..in.seconds.  < 1800) 

Output:

 Duration..in.seconds.
1                   188
2                   453
3                   188
4                   453
5                   188
6                   453
7                   188
8                   453

CodePudding user response:

Try this:

## Loading the library
library(dplyr)

## Loading the data
dat = data.frame(Duration..in.seconds. = c("114",  "188",  "453",  "114" , "188" , "453" , "114" , "188" , "453" , "188" , "453",  "2000" ,"2000" ,"1900" ))

## Filtering
dat %>%
  filter(Duration..in.seconds. %in% c(180:1800))

  Duration..in.seconds.
1                   188
2                   453
3                   188
4                   453
5                   188
6                   453
7                   188
8                   453
  • Related