将 R 数据框列名作为字符串引用,仅给出列名

Reference R data frame column name as a string, given only the column name

我有一个数据框 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"

如果不能直接在函数(tf(df,"b"))中将列名作为字符串传递,可以使用deparse + substitute.

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"

我们可以使用 as_stringenquo/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"