Perhaps, we don't need a loop, use the filter_at
.
If we need to filter
rows having either of the 'Con' values are 1, then we use the any_vars
to quote that a predicate expression should be applied to the variables mentioned in the .predicate
(here we use the index. If we need the string names, then wrap it with vars(matches("Con"))
database %>%
filter_at(2:3, any_vars(.==1))
Suppose, if we need to have 1 for both the columns, use the all_vars
database %>%
filter_at(2:3, all_vars(.==1))
For multiple datasets, initiate a list
and store the output from each iteration inside it
tmp <- setNames(vector("list", length(varibles)), varibles)
for(i in seq_along(varibles)){
tmp[[i]] <- database %>%
filter_at(vars(varibles[i]), all_vars(. == 1))
}
Or with sym
from rlang
tmp <- setNames(vector("list", length(varibles)), varibles)
for(i in seq_along(varibles)){
tmp[[i]] <- database %>%
filter(UQ(rlang::sym(varibles[i])) == 1)
}
tmp
#$Con1
# ID Con1 Con2
#1 1 1 1
#2 2 1 0
#3 4 1 0
#4 8 1 0
#5 10 1 0
#$Con2
# ID Con1 Con2
#1 1 1 1
The above approaches were doing using R 3.4.1
and dplyr_0.7.2
. As the OP mentioned some difficulties in updating the R to a new version, we tried the get
approach using R 3.1.3
and dplyr_0.4.3
tmp <- setNames(vector("list", length(varibles)), varibles)
for(i in seq_along(varibles)){
tmp[[i]] <- database %>%
filter(get(varibles[i], envir = as.environment(.))==1)
}
tmp
#$Con1
# ID Con1 Con2
#1 1 1 1
#2 2 1 0
#3 4 1 0
#4 8 1 0
#5 10 1 0
#$Con2
# ID Con1 Con2
#1 1 1 1