簡體   English   中英

參考R數據框列名作為字符串,只給出列名

[英]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_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"

如果不能直接在 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