【问题标题】:Reference R data frame column name as a string, given only the column name引用 R 数据框列名作为字符串,仅给出列名
【发布时间】:2021-03-27 01:31:30
【问题描述】:

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

【问题讨论】:

  • 我不明白您的问题...当然,如果您有特定的索引,可以使用colnames(df)[index] 进行检查。或者你可以做index=which('A and B'==colnames(df)) 来查找列的索引是你要问的吗?
  • 我的问题出现在我正在编写的函数中。它的两个输入是数据框名称 (df) 和感兴趣的列名称 (SomeName)。在我的函数中,我想操作 SomeName 中的值,并且我还想打印一个使用 SomeName 作为字符串的标题。这有帮助吗?
  • 你的意思是数据框的字符串名称吗?不是实际的数据框本身?
  • 我的意思是数据框的一列的字符串名称。假设我的数据框是 df,它有三个名为 a、b 和 c 的列。我的函数的输入是 df 和 b。在函数之外,我知道第二列是输入,但在列内我不知道。我想将作为函数输入的列名 b 转换为函数内的“b”。
  • 我添加了一个可重现的例子。

标签: r rlang


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    如果不能在函数中直接将列名作为字符串传递(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"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2020-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多