在dplyr中是否存在mapply等价物?

时间:2017-04-24 08:10:00

标签: r dplyr

使用dplyr:有没有办法循环数据框中的变量并将数据和变量名都传递给自定义函数?

我在基础R中使用mapply有一个解决方案。为了学习,我想知道是否有一种整洁的dplyr方法来实现相同的结果。

这是一个小例子,其中数据框中的每一列都通过添加常量进行转换。我希望添加的常量对于每个变量都是不同的,如myconstants中所列。

library(tidyverse)

mydata <- tibble(
  a = 1:5,
  b = 1:5,
  c = 1:5
)
myconstants <- tibble(
  a = 10,
  b = 20
)
custom_function <- function (x, y, k) {
  constant <- if (is.null(k[[y]])) 0 else k[[y]]
  x + constant
}

# solution in base R
foo <- mapply(
  custom_function, 
  mydata, 
  names(mydata), 
  MoreArgs = list(k = myconstants)
  ) %>%  
  as_tibble()

0 个答案:

没有答案