Home > Software design >  bind_row datafrane within a list in r
bind_row datafrane within a list in r

Time:07-29

I have a list of three dataframes as follow:

x1 <- data.frame(rnorm(5), rnorm(5))
x2 <- data.frame(rnorm(5), rnorm(5))
x3 <- data.frame(rnorm(5), rnorm(5))

list1 <- list(x1,x2,x3)
list1

I was trying to combine x1 to x2and x3 respectivelly using for loop with bind_row function like this:

df <- list()
for(i in 2: length(list1)){
  df[[i]] <- bind_rows(list1[1], list1[i])
}

The output that I got contains three elements with the first element as NULL value. I would like to remove this first element of the outcome list. How can I do that with my for loop here. I already did exlcude this by doing seperately but now I would like to do that with for loop.

CodePudding user response:

The reason why your first element is NULL is that df is an empty list to which you are assigning a 2nd and 3rd element but not a first element (since the for loop starts at 2). Simply assign the results to df[[i-1]] instead of df[[i]] so that the indexing starts at 1.

x1 <- data.frame(rnorm(5), rnorm(5))
x2 <- data.frame(rnorm(5), rnorm(5))
x3 <- data.frame(rnorm(5), rnorm(5))

list1 <- list(x1,x2,x3)

df <- list()
for(i in 2:length(list1)){
  df[[i - 1]] <- dplyr::bind_rows(list1[[1]], list1[[i]])
}

resulting in

df
#> [[1]]
#>      rnorm.5.  rnorm.5..1
#> 1   0.5357839 -0.01977554
#> 2   0.3767749  0.08128024
#> 3  -1.4592968  0.32772859
#> 4   1.1320294  0.11573657
#> 5  -1.6258767  0.89518999
#> 6   1.9629658 -0.31006782
#> 7   1.2439470  0.33417400
#> 8  -0.2733596  0.82149212
#> 9  -0.5620108  2.25258025
#> 10 -0.2034522 -1.20062231
#> 
#> [[2]]
#>       rnorm.5.  rnorm.5..1
#> 1   0.53578394 -0.01977554
#> 2   0.37677495  0.08128024
#> 3  -1.45929675  0.32772859
#> 4   1.13202945  0.11573657
#> 5  -1.62587667  0.89518999
#> 6   0.23592057  1.80902101
#> 7  -0.31696084  0.71427818
#> 8   0.23018058  0.92512042
#> 9   0.08847981 -0.26462483
#> 10 -0.24086157 -0.66625234

Created on 2022-07-28 by the reprex package (v2.0.1)

  • Related