我试图通过传递一个变量列表以首先按升序使用,一个变量按降序(最后按排列顺序)来动态排列数据帧。每次迭代都选择顶行并存储另一个数据框。下面的示例仅在传递单个降序变量时有效,但我无法使其与变量列表一起使用。
top_n_order <- function(df,n, expr_var, ... ){
expr_var <- enquo(expr_var)
dots <- list(...)
expr_order <- enquos(...)
if (!is_empty(dots)){
arrange_call <- lazyeval::interp(~ list(x,desc(y)), x=expr_order, y=expr_var)
selected_df <- df %>%
arrange_(.dots = list(arrange_call)) %>%
rownames_to_column("model_name") %>%
select(mpg, cyl, !! expr_var) %>%
head(n)
selected_df
}else{
selected_df <- df %>%
arrange(desc(!! expr_var)) %>%
rownames_to_column("model_name") %>%
select(model_name, mpg,cyl, !! expr_var) %>%
head(n)
selected_df
}
}
v_cols <- colnames(mtcars)
cars_top_df <- data.frame()
top_n_order(mtcars, 5, as.name(v_cols[3]) ) ##Works
for(i in 1:length(v_cols)){
v_order <- lapply(as.list(v_cols[-i]), as.name)
tmp_selected <- top_n_order(mtcars, 5, as.name(v_cols[i]), v_order )
cars_top_df <- bind_rows(cars_top_df,tmp_selected)
}
cars_top_df %>%
arrange(model_name)