我想创建一个 Select 两列的函数,一列基于函数的输入,第二列在被 Select 的第一列的前缀为"Other_"(在本例中为"种"和"Other_种").而不向该函数添加另一输入.

library(tidyverse)
iris_df <- iris %>%
  mutate(other_Species = Species)

iris_fn <- function (df, col){
df%>%
select(all_of(col, paste0("other_",col)))
}

iris_fn(df=iris_df, col="Species")

推荐答案

Transform "other_Species" in a symbol first. And all_of accepts only one argument at a time.
Another option, like it is said in comment, is to combine both character vectors with c().

你说all_of()一次只接受一个字符串是什么意思?它接受一个字符向量,这样你就可以在函数中使用select(all_of(c(col, paste0("other_", col)))),如果你正在传递一个字符串,就不需要转换成符号.

suppressPackageStartupMessages(
  library(tidyverse)
)
iris_df <- iris %>%
  mutate(other_Species = Species)

iris_fn <- function (df, col){
  other_col <- sym(paste0("other_", col))
  df%>%
    select(all_of(col), all_of(other_col))
}

iris_fn(df = iris_df, col = "Species") %>% head()
#>   Species other_Species
#> 1  setosa        setosa
#> 2  setosa        setosa
#> 3  setosa        setosa
#> 4  setosa        setosa
#> 5  setosa        setosa
#> 6  setosa        setosa

创建于2024-01-25年第reprex v2.0.2

R相关问答推荐

从嵌套列表中智能提取线性模型系数

使用R中相同值创建分组观测指标

修改用R编写的用户定义函数

在R中无法读入具有Readxl和lApply的数据集

多个模拟序列间的一种预测回归关系

可以替代与NSE一起使用的‘any_of()’吗?

plotly hover文本/工具提示在shiny 中不起作用

根据现有列的名称和字符串的存在进行变异以创建多个新列

DEN扩展包中的RECT树形图出现异常行为

SHINY:使用JS函数应用的CSS样式显示HTML表格

使用RSelenium在R中抓取Reddit时捕获多个标签

有没有可能用shiny 的书签恢复手风琴面板?

在使用具有Bray-Curtis相似性的pvCluust时计算p值

以不同于绘图中元素的方式对GG图图例进行排序

是否有一个R函数可以输出在输入的字符向量中找到的相应正则表达式模式?

有毒元素与表观遗传年龄的回归模型

如何在Quarto中使用美人鱼图表中的标记来加粗文本

组合名称具有模式的列表的元素

在分面的ggplot2条形图中对条形图进行排序,并省略每组未使用的系数级别

基于已有ID列创建唯一ID