简体   繁体   English

如何在 R 中的单个 dataframe 上迭代地应用 function?

[英]How to apply a function iteratively over a single dataframe in R?

I'm trying to turn this operation into a function where I could set the n argument and without using for loop .我正在尝试将此操作转换为 function ,我可以在其中设置n参数而不使用for loop This example is for 3 times.这个例子是3次。 I thought I could do it with purrr::reduce but it needs a list (?).我想我可以用purrr::reduce来做,但它需要一个列表(?)。

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

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
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)代表 package (v2.0.1) 于 2021 年 11 月 26 日创建

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM