且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在dplyr中更改循环

更新时间:2023-11-03 08:49:28

这是一种利用来自 rlang 的 dplyr 中包含的整洁的评估助手"的方法.code>包.

Here's an approach that makes use of some 'tidy eval helpers' included in dplyr that come from the rlang package.

基本思想是在 mutate()中创建一个新列,其名称基于for循环提供的字符串.

The basic idea is to create a new column in mutate() whose name is based on a string supplied by a for-loop.

library(dplyr)

grouped_data <- Lake_Champlain_long.term_monitoring_1992_2016 %>% 
  group_by(StationID,Test) %>% 
  arrange(StationID,Test,VisitDate)

for (lag_size in c(1, 5, 10, 15, 20)) {

  new_col_name <- paste0("lag_result_", lag_size)

  grouped_data <- grouped_data %>% 
    mutate(!!sym(new_col_name) := lag(Result, n = lag_size, default = NA))
}

sym(new_col_name):= 是在使用