小编Sea*_*ams的帖子

使用dplyr和purrr重复变量变量

我在R中自学成才,这是我的第一个StackOverflow问题.如果这是一个明显的问题,我道歉; 请善待.

我的问题的简短版本
我编写了一个自定义函数来计算变量年份的变化百分比.我想使用purrrmap_at函数将我的自定义函数应用于变量名称的向量.我的自定义函数在应用于单个变量时有效,但在使用时将其链接失败map_a

我的自定义功能

calculate_delta <- function(df, col) {

  #generate variable name
  newcolname = paste("d", col, sep="")

  #get formula for first difference.
  calculate_diff <- lazyeval::interp(~(a + lag(a))/a, a = as.name(col))

  #pass formula to mutate, name new variable the columname generated above
  df %>% 
        mutate_(.dots = setNames(list(calculate_diff), newcolname)) }
Run Code Online (Sandbox Code Playgroud)

当我将此函数应用于mtcars数据集中的单个变量时,输出与预期一致(尽管显然结果的含义是非敏感的).

calculate_delta(mtcars, "wt")
Run Code Online (Sandbox Code Playgroud)

尝试使用Purrr将函数应用于字符向量

我认为我无法概念化map_at如何将参数传递给函数.我可以在网上找到的所有示例片段都使用map_at和类似的函数is.character,这些函数不需要额外的参数.以下是我尝试使用该功能的尝试purrr.

vars <- c("wt", "mpg")
mtcars %>% map_at(vars, calculate_delta)
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误信息

粘贴错误("d",col,sep =""):缺少参数"col",没有默认值

我想这是因为map_at被路过varsdf,而不是传递参数的col …

r dplyr purrr non-standard-evaluation

5
推荐指数
1
解决办法
2535
查看次数

标签 统计

dplyr ×1

non-standard-evaluation ×1

purrr ×1

r ×1