[英]Reference R data frame column name as a string, given only the column name
我有一个数据框 df。 它有一个名为b
的列。 我知道这个列名,虽然我不知道它在数据框中的 position。 我知道 colnames(df) 会给我一个字符串向量,它是所有列的名称,但我不知道如何获取这个特定列的字符串。 换句话说,我想获得字符串“b”。 我怎样才能做到这一点? 我想这可能涉及我难以理解的 rlang package。
这是一个例子:
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"
我们可以将as_string
与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"
如果不能直接在 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.