以字符串形式引用R数据框列名,仅给定列名

以字符串形式引用R数据框列名,仅给定列名,r,rlang,R,Rlang,我有一个数据帧df。它有一个名为b的列。我知道这个列名,尽管我不知道它在数据框中的位置。我知道colnames(df)将给我一个字符串向量,它是所有列的名称,但我不知道如何为这个特定列获取字符串。换句话说,我想获得字符串“b”。我该怎么做?我想这可能涉及rlang包,我很难理解 下面是一个例子: library(rlang) library(tidyverse) a <- c(1:8) b <- c(23,34,45,43,32,45,68,78) c <- c(0.34,0

我有一个数据帧df。它有一个名为
b
的列。我知道这个列名,尽管我不知道它在数据框中的位置。我知道colnames(df)将给我一个字符串向量,它是所有列的名称,但我不知道如何为这个特定列获取字符串。换句话说,我想获得字符串“b”。我该怎么做?我想这可能涉及rlang包,我很难理解

下面是一个例子:

library(rlang)
library(tidyverse)

a <- c(1:8)
b <- c(23,34,45,43,32,45,68,78)
c <- c(0.34,0.56,0.97,0.33,-0.23,-0.36,-0.11,0.17)
df <- data.frame(a,b,c)

tf <- function(df,MYcol) {
  print(paste0("The name of the input column is ",MYcol)) # does not work
  print(paste0("The name of the input column is ",{{MYcol}})) # does not work
  y <- {{MYcol}} # This gives the values in column b as it shoulkd
}
z <- tf(df,b) # Gives undesired values - I want the string "b"
z
库(rlang)
图书馆(tidyverse)

a如果无法在函数(
tf(df,“b”)
)中直接将列名作为字符串传递,则可以使用
deparse
+
替换

tf <- function(df,MYcol) {
  col <- deparse(substitute(MYcol))
  print(paste0("The name of the input column is ",col)) 
  return(col)
}

z <- tf(df,b) 
#[1] "The name of the input column is b"
z
#[1] "b"

tf我们可以使用
作为字符串
enquo/ensym

tf <- function(df, MYcol) {
 
 mycol <- rlang::as_string(rlang::ensym(MYcol))
  print(glue::glue("The name of the input column is {mycol}")) 
  return(mycol)
}

z <- tf(df,b) 
The name of the input column is b
z
#[1] "b"

tf我不明白你的问题。。。当然,如果您心中有一个特定的索引,可以使用
colnames(df)[index]
检查它。或者您可以执行
index=which('A和B'==colnames(df))
来查找列的索引,这就是您要问的吗?我的问题出现在我正在编写的函数中。它的两个输入是数据帧名称(df)和感兴趣的列名(SomeName)。在我的函数中,我想操作SomeName中的值,还想打印一个将SomeName用作字符串的标题。这有用吗?你是指数据帧的字符串名称吗?不是实际的数据帧本身?我指的是数据帧中一列的字符串名称。假设我的数据帧是df,它有三列,分别命名为a、b和c。my函数的输入为df和b。在函数外部,我知道第二列是输入,但在该列内部,我不知道。我想将作为函数输入的列名b转换为函数中的“b”。