Sometimes I store every result in my initialized vector/matrix.

Here is the data.

##   people    values day
## 1   john  8.125192   1
## 2  teddy 10.624786   1
## 3  clare  9.755946   1
## 4   john  8.320525   2
## 5  teddy  8.758530   2
## 6   john  9.597217   3
## 7  teddy 10.947977   3
## 8  clare  9.416608   3

Now the code. I want to find the days where I have responses from John, Teddy, and Clare (as you can tell, I only have responses from all three of them on days 1 and 3).

use_days <- numeric(length(unique(df$days))) # initialized vector counter <- 0 select_days <- c(1, 2, 3) for(i in 1:length(select_days)){ counter <- counter + 1 # select the i-th day filter_data <- df %>% filter(day == select_days[i]) # are there three responses on this day? if(length(filter_data$day) == 3){
use_days[counter] <- filter_data$day } } use_days ## [1] 1 NA 3 That code works, but what if I don’t want to store that NA during the second iteration? To only store successful output, put the counter in the “if statement.” use_days <- numeric(length(unique(df$days))) # initialized vector
counter <- 0

select_days <- c(1, 2, 3)

for(i in 1:length(select_days)){

# select the i-th day

filter_data <- df %>%
filter(day == select_days[i])

# are there three responses on this day?

if(length(filter_data$day) == 3){ counter <- counter + 1 # HERE IS THE CHANGE use_days[counter] <- filter_data$day
}
}

use_days
## [1] 1 3

Bo$$^2$$m =)