简体   繁体   English

参考R数据框列名作为字符串,只给出列名

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

I have a data frame df.我有一个数据框 df。 It has a column named b .它有一个名为b的列。 I know this column name, although I do not know its position in the data frame.我知道这个列名,虽然我不知道它在数据框中的 position。 I know that colnames(df) will give me a vector of character strings that are the names of all the columns, but I do not know how to get a string for this particular column.我知道 colnames(df) 会给我一个字符串向量,它是所有列的名称,但我不知道如何获取这个特定列的字符串。 In other words, I want to obtain the string "b".换句话说,我想获得字符串“b”。 How can I do that?我怎样才能做到这一点? I imagine this may involve the rlang package, which I have difficulty understanding.我想这可能涉及我难以理解的 rlang package。

Here's an example:这是一个例子:

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"

We can use as_string with enquo/ensym我们可以将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"

If you cannot pass column name as string in the function ( tf(df,"b") ) directly, you can use deparse + substitute .如果不能直接在 function ( 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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM