Home > OS >  How to apply a function iteratively over a single dataframe in R?
How to apply a function iteratively over a single dataframe in R?

Time:11-27

I'm trying to turn this operation into a function where I could set the n argument and without using for loop. This example is for 3 times. I thought I could do it with purrr::reduce but it needs a list (?).

tibble::add_row(tibble::add_row(tibble::add_row(df, .before = 1), .before = 1), .before = 1)

CodePudding user response:

reduce(rep(list(add_row), 3), ~.y(.x, .before = 1), .init =df)

   x  y
1 NA NA
2 NA NA
3 NA NA
4  1  3
5  2  4

CodePudding user response:

library(tidyverse)

add_row_n <- function(df, n) {
  walk(1:n, ~ {df <<- add_row(df, .before = 1)})
  df
}

tibble() %>% 
  add_row_n(3)
#> # A tibble: 3 × 0

tibble(x = 1, y = 2) %>% 
  add_row_n(3)
#> # A tibble: 4 × 2
#>       x     y
#>   <dbl> <dbl>
#> 1    NA    NA
#> 2    NA    NA
#> 3    NA    NA
#> 4     1     2

Created on 2021-11-26 by the reprex package (v2.0.1)

CodePudding user response:

How about

add_n_rows = function(df, n) {
    
    new.rows = as.data.frame(matrix(NA, nrow=n, ncol=ncol(df)))
    colnames(new.rows) <- colnames(df)
    
    df %>% add_row(new.rows, .before = 1)        
}

# test
df = data.frame(x = rnorm(10), y = rnorm(10))
add_n_rows(df, 3)
  • Related