Dplyr非标准评估-需要帮助

时间:2018-09-10 15:30:12

标签: r dplyr nse

我正在使用dplyr中的非标准评估(NSE)迈出第一步。 请考虑以下代码段:它使用一个tibble,根据一列中的值对其进行排序,并将n-k个较低的值替换为“其他”。

例如参见:

library(dplyr)

df <- cars%>%as_tibble

k <- 3

df2 <- df %>%
arrange(desc(dist))  %>% 
mutate(dist2 = factor(c(dist[1:k],
                rep("Other", n() - k)),
                levels = c(dist[1:k], "Other")))

我想要的是这样的函数:

df2bis<-df %>% sort_keep(old_column, new_column, levels_to_keep)

产生相同的结果,其中old_column列“ dist”(我用于对数据集进行排序的列),new_column(我生成的列)为“ dist2”,而levels_to_keep为“ k”(我明确保留的值数) )。 我迷上了enquo,quo_name等...

任何建议都值得赞赏。

2 个答案:

答案 0 :(得分:1)

您可以这样做:

library(dplyr)

sort_keep=function(df,old_column, new_column, levels_to_keep){
  old_column = enquo(old_column)
  new_column = as.character(substitute(new_column))
  df %>%
    arrange(desc(!!old_column))  %>% 
    mutate(use = !!old_column,
           !!new_column := factor(c(use[1:levels_to_keep],
                                  rep("Other", n() - levels_to_keep)),
                                levels = c(use[1:levels_to_keep], "Other")),
           use=NULL)
}


 df%>%sort_keep(dist,dist2,3)

答案 1 :(得分:0)

像这样吗?

old_column = "dist"
new_column = "dist2"
levels_to_keep = 3

command = "df2bis<-df %>% sort_keep(old_column, new_column, levels_to_keep)"
command = gsub('old_column', old_column, command)
command = gsub('new_column', new_column, command)
command = gsub('levels_to_keep', levels_to_keep, command)
eval(parse(text=command))