I'm very new to R (like, just this week :)), and have what I think is a basic question...
I'm doing a sequence of searches in a for loop and putting the results in a table. The code below works.
library(tidyverse)
# Set up fake data
xA <- c(1:5)
xB <- c(11:15)
xC <- c(21:25)
df <- tibble(xA,xB,xC)
df
#> # A tibble: 5 x 3
#> xA xB xC
#> <int> <int> <int>
#> 1 1 11 21
#> 2 2 12 22
#> 3 3 13 23
#> 4 4 14 24
#> 5 5 15 25
AllResults <- c() # need an empty vector first
for (xAlook in 2:4) {
df %>%
filter(xA==xAlook) %>% # get results that match criteria
select(xA,xB) -> LocalResults # only care about columns xA and xB
AllResults <- bind_rows(AllResults,LocalResults) # append to AllResults
}
AllResults
#> # A tibble: 3 x 2
#> xA xB
#> <int> <int>
#> 1 2 12
#> 2 3 13
#> 3 4 14
However, it seems like I shouldn't need to define LocalResults, but that I ought to be able to simply pipe it into bind_rows, like I've done below. However, as you can see, that didn't work.
Any suggestions?
library(tidyverse)
# Set up fake data
xA <- c(1:5)
xB <- c(11:15)
xC <- c(21:25)
df <- tibble(xA,xB,xC)
AllResults <- c() # need an empty vector first
for (xAlook in 2:4) {
df %>%
filter(xA==xAlook) %>% # get results that match criteria
select(xA,xB) %>% # only care about columns xA and xB
bind_rows(AllResults) # append to AllResults
}
AllResults
#> NULL