r - 将 dplyr 的变量选择功能扩展到自定义函数

标签 r dplyr

我想知道是否有一种简单的方法可以在我自己的自定义函数中使用 dplyr 的变量选择函数。通过 dplyr 的变量选择函数,我的意思是:https://github.com/hadley/dplyr/blob/master/R/select-utils.R

或者,如果您熟悉 dplyr,例如“contains”、“one_of”、“starts_with”等。

我想要做的是编写一个仅对某些变量进行操作的函数:

# note: pseudo code
foo = function(df, vars){
  for (var in vars){
     df$var = as.character(df$var)
  }
}

我知道 dplyr 的“mutate_each”函数,它允许我执行此操作,但我必须编写一个对向量进行操作的函数,而不是编写一个对 data.frame 进行操作的函数。

我的问题的目的是能够更干净地向数据处理管道添加自定义函数。例如,我想最终这样做:

df %>%
  foo(starts_with("varname"))

而不是

df %>%
  mutate_each(funs(foo), starts_with("varname"))

我希望这是有道理的。谢谢!

最佳答案

你想要

df %>%
  foo(starts_with("varname"))

可以用以下方法解决

df %>% select(starts_with("varname")) %>% foo

如果您确实想要一个功能:

select_and_foo <- function(df,varname) {
    df %>% select(starts_with(varname)) %>% foo %>% return
}

然后

df %>% select_and_foo("varname")

示例

# create sample data
set.seed(16)
sampledf <- matrix(rnorm(50), ncol = 10) %>% as.data.frame() %>% set_names(paste0(c(rep("H",5),rep("O",5)),1:10))

> sampledf
          H1          H2         H3         H4         H5        O6          O7         O8         O9         O10
1  0.4764134 -0.46841204  1.8471821 -1.6630805 -1.6477976 1.5274670 -0.67252558  0.2805551 -1.3253531  0.28390672
2 -0.1253800 -1.00595059  0.1119334  0.5759095 -0.3141739 1.0541781  0.13259853  0.5447834  2.0651357  0.12157699
3  1.0962162  0.06356268 -0.7460373  0.4727601 -0.1826816 1.0300710 -0.07092735  0.1308698  0.2421730  0.56634411
4 -1.4442290  1.02497260  1.6582137 -0.5427317  1.4704785 0.8401609 -0.94269547  0.2818444 -0.3490972  0.56903290
5  1.1478293  0.57314202  0.7217206  1.1276871 -0.8658988 0.2169647 -1.02203100 -0.2927308 -0.6308124 -0.09058676


# define a function that operates on dataframes and returns a dataframe
foo = . %>% solve %>% t %>% as.data.frame

# et voila
> sampledf %>% select(starts_with("H")) %>% foo
          H1         H2        H3          H4          H5
1  0.3004043 -0.2011219 0.2233852 -0.28712106  0.07735365
2  0.3557121 -0.9996712 0.4830006  0.30975840  0.61582865
3  1.7020360 -0.8657610 0.4686327 -0.35050079  1.61728993
4  0.4993172 -0.2886113 0.4811486 -0.04590702  0.81210612
5 -0.2118682  0.4379735 0.1178755  0.42998574 -0.48759158

关于r - 将 dplyr 的变量选择功能扩展到自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34046607/

相关文章:

r - data.table 中字符变量的 order() 如何工作?

r - 识别两列之间的拼写错误

r - 根据前一行中多个变量的值对行进行条件过滤

r - 变异以在每一行中创建最小值

r - 我可以使用 mutate() 和 across() 根据许多其他列来改变许多列吗?

r - 如何修改多个数据框而不创建它们的列表然后使用 lapply?

r - 将基于记录的列表/对象展平到数据框中

r - if(ncol.matrix < rep) { : argument is of length zero 中的错误

检索 R 中的最佳簇数

r - 从分组数据中选择两个随机且连续的行