2
votes

I am looking for an elegant way to filter the values of a specific group of big data.frame based on multiple conditions.

My data frame looks like this.

data=data.frame(group=c("A","B","C","A","B","C","A","B","C"), 
                time= c(rep(1,3),rep(2,3), rep(3,3)), 
                value=c(0.2,1,1,0.1,10,20,10,20,30))

  group time value
1     A    1   0.2
2     B    1   1.0
3     C    1   1.0
4     A    2   0.1
5     B    2  10.0
6     C    2  20.0
7     A    3  10.0
8     B    3  20.0
9     C    3  30.0

I would like only for the time point 1 to filter out all the values that are smaller than 1 but bigger than 0.1

I want my data.frame to look like this.

  group time value
1     A    1   0.2
4     A    2   0.1
5     B    2  10.0
6     C    2  20.0
7     A    3  10.0
8     B    3  20.0
9     C    3  30.0

Any help is highly appreciated.

3
Does this answer your question? R dplyr - filter by multiple conditions - user438383
Not really. I had to edit my question to make it more clear. Thank you for your comment. It was helpful - LDT

3 Answers

3
votes

With dplyr you can do

library(dplyr)

data %>% filter(!(time == 1 & (value <= 0.1 | value >= 1))) 

#   group time value
# 1     A    1   0.2
# 2     A    2   0.1
# 3     B    2  10.0
# 4     C    2  20.0
# 5     A    3  10.0
# 6     B    3  20.0
# 7     C    3  30.0
1
votes

Or if you have too much free time and you decided to avoid dplyr:

ind <- with(data, (data$time==1 & (data$value > 0.1 & data$value < 1)))
ind <- ifelse((data$time==1) & (data$value > 0.1 & data$value < 1), TRUE, FALSE)
#above two do the same

data$ind <- ind
data <- data[!(data$time==1 & ind==F),]
data$ind <- NULL

  group time value
1     A    1   0.2
4     A    2   0.1
5     B    2  10.0
6     C    2  20.0
7     A    3  10.0
8     B    3  20.0
9     C    3  30.0
0
votes

Another simple option would be to use subset twice and then append the results in a row wise manner.

rbind(
  subset(data, time == 1 & value > 0.1 & value < 1),
  subset(data, time != 1)
)

#    group time value
# 1     A    1   0.2
# 4     A    2   0.1
# 5     B    2  10.0
# 6     C    2  20.0
# 7     A    3  10.0
# 8     B    3  20.0
# 9     C    3  30.0