You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R函数中对添加后缀后的指定列使用arrange函数排序?

解决R函数中按添加后缀的列排序的问题

你的代码里arrange(paste0(col,".suffix"))无法生效,原因是arrange()需要的是列对象,而非字符串形式的列名。下面提供两种可行的修改方式:

方法1:使用.all_of()(推荐,dplyr 1.0.0+适用)

library(tidyverse)

fn <- function(df, col){
  df %>%
    rename_with(~ paste0(., ".suffix")) %>%
    arrange(.all_of(paste0(col, ".suffix")))
}

fn(df = iris, col = "Sepal.Width")

.all_of()可以将字符串格式的列名转换为dplyr能识别的列选择器,完美适配这里的需求。

方法2:使用tidyeval语法(sym + !!)

library(tidyverse)

fn <- function(df, col){
  target_col <- sym(paste0(col, ".suffix"))
  df %>%
    rename_with(~ paste0(., ".suffix")) %>%
    arrange(!!target_col)
}

fn(df = iris, col = "Sepal.Width")

sym()把拼接后的列名字符串转为符号对象,!!(双感叹号)在dplyr函数中对这个符号求值,让arrange()识别到对应的列。

内容的提问来源于stack exchange,提问作者Basil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 10:32:32