Sometimes I store every result in my initialized vector/matrix.
Here is the data.
people values day
1 john 9.991020 1
2 teddy 8.052606 1
3 clare 9.213088 1
4 john 8.819214 2
5 teddy 8.364933 2
6 john 10.670680 3
7 teddy 9.233042 3
8 clare 11.330505 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 =)