Valtyr
Valtyr

Reputation: 123

Add conditions to a logical vector with a loop [r]

I want to make a series of plots based on increasingly narrowing sets of conditions. Here is an exsample data frame:

    df <- data.frame(A=rep(letters[1:4],4),B=sample(1:5, 16, replace=TRUE),C=sample(1:500, 16, replace=TRUE))

Here are example conditions:

    cond_1 <- df$A!='a'
    cond_2 <- df$A!='b'
    cond_3 <- df$C < 400 & df$C > 100

Can you help me find a convenient way to add the conditions to a plot like say:

    plot(df$B)
    plot(df$B[cond_1])
    plot(df$B[cond_1 & cond_2])
    plot(df$B[cond_1 & cond_2 & cond_3])

I have tried making a loop but I'm having trouble making the conditions add up nicely.

    cond_list <- list(cond_1,cond_2,cond_3)
    list_1 <- list()
    list_2 <- list()
    for(i in 1:3){
    list_1<-  cond_list[i]
    list_2[i] <- list_1
    mat_1 <- do.call(cbind,list_2)
    plot(df$B[c(mat_1[,i],mat_1[,i-1])])
    }

Upvotes: 1

Views: 160

Answers (1)

Paul Hiemstra
Paul Hiemstra

Reputation: 60944

I would use dplyr for this:

library(dplyr)

# Make a list of the required conditions    
condition_list = c('A != "a"', 
                   'A != "b"', 
                   'C < 400 & C > 100')
# Filter using the first condition
> df %>% filter_(.dots = condition_list[1])
   A B   C
1  b 1 399
2  c 4 208
3  d 4 331
4  b 5  21
5  c 3 211
6  d 1 408
7  b 4 438
8  c 2 165
9  d 2 120
10 b 5  43
11 c 3  23
12 d 1 181
# Filter using the first and second condition
> df %>% filter_(.dots = condition_list[1:2])
  A B   C
1 c 4 208
2 d 4 331
3 c 3 211
4 d 1 408
5 c 2 165
6 d 2 120
7 c 3  23
8 d 1 181
# Filter using all three conditions
> df %>% filter_(.dots = condition_list[1:3])
  A B   C
1 c 4 208
2 d 4 331
3 c 3 211
4 c 2 165
5 d 2 120
6 d 1 181

You can mix and match as you please. After applying the filter_, you can input that data into plot.

Note I use filter_ version of filter, which allows you to pass the filter expressions as a string (see also this article). In addition, the %>% is a pipe, very comparable to the use of pipes in bash (linux), see a tutorial I wrote for some more in-depth discussion.

Upvotes: 2

Related Questions