5

我在使用 dplyr 重命名函数中的列时遇到困难。我已经找到了关于非标准评估和 enquo 使用的有用帖子(例如,http ://dplyr.tidyverse.org/articles/programming.html和 在自定义 dplyr 函数中更改结果变量的名称)。最终目标是使用该函数对每个组进行汇总,然后将列重命名为比原始变量名称更有意义的名称。

这是一个简单的示例,除了注释掉的行之外它都有效。

library(tidyverse)

myfunc <- function(df, groupvar, colvar, grouplab, collab) {
  groupvar <- enquo(groupvar)
  colvar <- enquo(colvar)
  grouplab <- enquo(grouplab)  # quo_name instead?
  collab <- enquo(collab)  # quo_name instead?

t <- df %>%
  select(!!groupvar, !!colvar) %>%
  group_by(!!groupvar, !!colvar) %>%
  summarise(
    Frequencies = length(!!colvar),
    Percentages = length(!!colvar) / nrow(df)
    ) %>%
  mutate(
    Frequencies = scales::comma(Frequencies),
    Percentages = scales::percent(Percentages)
    ) #%>%
# rename(
#    (!!grouplab) = !!groupvar,  # add a more descriptive grouping var label
#    (!!collab) = !!colvar)  # add a more descriptive column var label

# Error: unexpected '=' in: rename((!!grouplab) = "

...  # code to create an xtable, print it into LaTeX
}

myfunc <- (df = mtcars, groupvar = gear, colvar = cyl, grouplab = "Vehicle Gears", collab = "Vehicle Cylinders")
# I purposely made grouplab and collab have a space in case that changes anything. 

在函数之外,相关部分将简单地阅读:mtcars <- mtcars %>% rename("Vehicle Cylinders" = cyl, "Vehicle Gears" = gear)

我一定被重命名在函数中与函数之外的操作方式所困扰。有什么建议吗?我愿意接受建议。

更新
这是一种方法。我宁愿不把变量名放在字符串中,但不知道这里有什么办法。接受建议。

library(tidyverse)
library(xtable)
data(mtcars)

t_groupedfreqprop <- function(df, groupvar, colvar, grouplab, collab, plotname) {
groupvar2 <- rlang::sym(groupvar)
colvar2 <- rlang::sym(colvar)
grouplab <- rlang::sym(grouplab)
collab <- rlang::sym(collab)

t <- df %>%
  select(!!groupvar2, !!colvar2) %>%
  group_by(!!groupvar2, !!colvar2) %>%
  summarise(
    Frequencies = length(!!colvar2),
    Percentages = length(!!colvar2) / nrow(df)
  ) %>%
  mutate(
    Frequencies = scales::comma(Frequencies),
    Percentages = scales::percent(Percentages)
  ) %>%
  rename(
    !!grouplab := !!rlang::sym(groupvar2),
    !!collab := !!rlang::sym(colvar2)
  )

# remainder of function removed
}

t_groupedfreqprop(df = mtcars, groupvar = "gear", colvar = "cyl", grouplab = "Vehicle Gears", collab = "Vehicle Cylinders")
4

2 回答 2

11

:=如果您希望在表达式的 LHS 上以编程方式分配名称,请使用。

x <- "mpg"
xnew <- "mpg2"
rename(mtcars, !!xnew := !!rlang::sym(x))
于 2017-08-11T23:05:26.853 回答
6

要一次重命名多个列,您必须使用!!!

x <- c("mpg", "cyl")
xnew <- paste(x, 2, sep = ".")
names(x) <- xnew
rename(mtcars, !!!x)
于 2018-01-29T15:19:36.450 回答