append a list from a for loop

Hi there,

Looking at the function it is not clear what you are trying to do here, but chances are you don't even need a loop with IF statement if you just want to extract or rearrange data...

Next time try to generate a reprex instead of using a screenshot. A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

That said, here are two generic examples of appending things to a data frame, the first one just using base R, the other one using tidyverse functions.

#Base R
myData = data.frame(
  a = character(),
  b = numeric()
)

for(i in 1:10){
  if(i %% 2 == 0){
    myData[nrow(myData)+1,] = list(i, runif(1))
  }
}
myData
#>    a         b
#> 1  2 0.5419549
#> 2  4 0.8368228
#> 3  6 0.2262199
#> 4  8 0.1070023
#> 5 10 0.8860279

#Tidyverse mapping
library(tidyverse)

map_df(1:10, function(i){
  
  if(i %% 2 == 0){
    tibble(a = i, b = runif(1))
  }
  
})
#> # A tibble: 5 x 2
#>       a     b
#>   <int> <dbl>
#> 1     2 0.268
#> 2     4 0.865
#> 3     6 0.269
#> 4     8 0.701
#> 5    10 0.246

Created on 2021-05-03 by the reprex package (v2.0.0)

Hope this helps,
PJ

1 Like