本文介绍了tidyverse中的重复变异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下小标题和以下矢量:

consider the following tibble and the follwing vector:

library(tidyverse)
a <- tibble(val1 = 10:15, val2 = 20:25)
params <- 1:3

我还有一个函数 myfun ,该函数将任意长度的向量和一个整数作为输入,并返回相同长度的向量。出于演示目的,您可以想到

Also I have a function myfun which takes a vector of arbitrary length and an integer as input and returns an vector of the same length. For demonstration purposes you can think of

myfun <- function(x, k) dplyr::lag(x, k)

我想创建以下对象:对于 a 并为 params 中的每个元素创建一个由 myfun(col,params [i])
在上面的玩具示例中,例如可以这样实现:

I want to create the follwing: for each column in a and for each element in params I want to create a new column given by myfun(col, params[i]) .In the toy example above this could for example be achieved like this:

a %>% mutate_at(1:2, funs(run1 = myfun), k = params[1]) %>% 
  mutate_at(1:2, funs(run2 = myfun), k = params[2]) %>% 
  mutate_at(1:2, funs(run3 = myfun), k = params[3]) 

是否有更优雅的方法可以做到这一点?如果参数很长,那么此解决方案将变得不可行。当然,可以使用for循环来做到这一点,但我认为tidyverse中可能有解决方案(也许使用 purrr :: map ?)

Is there a more elegant approach to do this? If params is very long then this solution becomes infeasible. Of course one could do this with a for loop, but I thought that there might be a solution within the tidyverse (maybe using purrr::map?)

谢谢!

推荐答案

以下是使用tidyverse的解决方案:

Here is a solution using tidyverse:

library(tidyverse)
a <- tibble(val1 = 10:15, val2 = 20:25)
params <- 1:3

#set the column names, add leading zeroes based om max(params)
run_names <- paste0("run", formatC(params, width = nchar(max(params)), flag = "0"))

#what functions to perform
lag_functions <- setNames(paste("dplyr::lag( ., ", params, ")"), run_names)
#perfporm functions 
a %>% mutate_at(vars(1:2), funs_(lag_functions ))

# # A tibble: 6 x 8
#    val1  val2 val1_run1 val2_run1 val1_run2 val2_run2 val1_run3 val2_run3
#   <int> <int>     <int>     <int>     <int>     <int>     <int>     <int>
# 1    10    20        NA        NA        NA        NA        NA        NA
# 2    11    21        10        20        NA        NA        NA        NA
# 3    12    22        11        21        10        20        NA        NA
# 4    13    23        12        22        11        21        10        20
# 5    14    24        13        23        12        22        11        21
# 6    15    25        14        24        13        23        12        22

这篇关于tidyverse中的重复变异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:30