如何将函数中的字符串转换为对象?

时间:2022-12-05 14:27:53

I would like to convert a string that I pass in a function into an object (or column name).

我想要将传入函数的字符串转换为对象(或列名)。

I know that this works:

我知道这行得通:

df <- data.frame(A = 1:10, B = 11:20)

test.function <- function(x)            
{
  z <- df[[x]]
  return(z)
}
test.function("A")

I don't want to use the [[.]] operator, because sometimes it is unpractical or even not applicable. I am interessted in a general method to convert a string into an "object". Therefore I tried the following:

我不想用[。[英语背诵文选因为有时它不实用,甚至不适用。我用一般的方法将一个字符串转换成一个“对象”。因此,我尝试了以下方法:

df <- data.frame(A = 1:10, B = 11:20)

test.function <- function(x)
{
  z <- get(paste("df$", x, sep = ""))
  return(z)
}
test.function("A")

or

df <- data.frame(A = 1:10, B = 11:20)

test.function <- function(x)
{
  z <- as.name(paste("df$", x, sep = ""))
  return(z)
}
test.function("A")

or

df <- data.frame(A = 1:10, B = 11:20)

test.function <- function(x)
{
  z <- df$as.name(x)
  return(z)
}
test.function("A")

I also tried to play around with the parse, do.call and eval functions. Unfortunatelly I failed

我还尝试了解析do。电话和eval函数。annihilate我失败了

4 个解决方案

#1


21  

The trick is to use parse. For instance:

诀窍是使用解析。例如:

> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
 [1]  1  2  3  4  5  6  7  8  9 10

See also this Q/A: Evaluate expression given as a string

还请参见这个Q/A:求值表达式作为字符串给出

#2


5  

I just got an upvote which brought me back after 5 years to this question. I still think that the correct answer is [[ despite the OP's request not to use it, but here's a way to dress up [[ as a more functional "function".

我刚得到了一个向上的投票,这让我在5年后回到了这个问题上。我仍然认为正确的答案是[尽管OP要求不使用它,但这里有一种打扮[作为一种更实用的"功能"]的方式。

df <-     structure(list(x = 1:3, y = 1:3), .Names = c("x", "y"), row.names = c(NA, 
-3L), class = "data.frame")

 test.function <- `[[`    # So simple, `test.function` now has all the features desired.
 df
 x y
 1 1
 2 2
 3 3
 test.function(df, "x")
#[1] 1 2 3

Or if it were desireable to hard code pulling an object named 'df' from the calling environment, a proposition that seems of dubious safety:

或者,如果它想要硬编码,从调用环境中提取一个名为“df”的对象,这似乎是一个值得怀疑的安全命题:

 test.df_txt <- function(var, dfn ='df' ){ get(dfn)[[var]] }
 test.df_txt("x")
#[1] 1 2 3

Original response (still not recommended):

原始回复(仍不推荐):

You can sidestep around the limitations of "$" if you are willing to use eval(parse(text=...)) :

如果您愿意使用eval(parse(text=…)):

 test.function <- function(x)  {
   z <- eval(parse( text=paste("df$", x, sep = "")), env=.GlobalEnv)
   return(z)
   }
test.function("A")
# [1]  1  2  3  4  5  6  7  8  9 10

BUT ... it is much better to use "[[". (My initial efforts at eval(parse()-ing were stuck at not knowing enough to use the "text" argument to parse.)

但是…最好使用"[]"。(我在eval(parse()-ing的最初工作是不知道如何使用“text”参数进行解析。)

#3


1  

In addition to eval(parse(text=YOUR_STRING)), you can use as.symbol as a potential alternative.

除了eval(parse(text=YOUR_STRING)),还可以使用as。符号作为一种潜在的选择。

#4


0  

You can create a variable name from a string using the assign operator, as in: assign("a_string", NULL)

您可以使用assign操作符从字符串中创建一个变量名,如:assign(“a_string”,NULL)

#1


21  

The trick is to use parse. For instance:

诀窍是使用解析。例如:

> x <- "A"
> eval(parse(text=paste("df$", x, sep = "")))
 [1]  1  2  3  4  5  6  7  8  9 10

See also this Q/A: Evaluate expression given as a string

还请参见这个Q/A:求值表达式作为字符串给出

#2


5  

I just got an upvote which brought me back after 5 years to this question. I still think that the correct answer is [[ despite the OP's request not to use it, but here's a way to dress up [[ as a more functional "function".

我刚得到了一个向上的投票,这让我在5年后回到了这个问题上。我仍然认为正确的答案是[尽管OP要求不使用它,但这里有一种打扮[作为一种更实用的"功能"]的方式。

df <-     structure(list(x = 1:3, y = 1:3), .Names = c("x", "y"), row.names = c(NA, 
-3L), class = "data.frame")

 test.function <- `[[`    # So simple, `test.function` now has all the features desired.
 df
 x y
 1 1
 2 2
 3 3
 test.function(df, "x")
#[1] 1 2 3

Or if it were desireable to hard code pulling an object named 'df' from the calling environment, a proposition that seems of dubious safety:

或者,如果它想要硬编码,从调用环境中提取一个名为“df”的对象,这似乎是一个值得怀疑的安全命题:

 test.df_txt <- function(var, dfn ='df' ){ get(dfn)[[var]] }
 test.df_txt("x")
#[1] 1 2 3

Original response (still not recommended):

原始回复(仍不推荐):

You can sidestep around the limitations of "$" if you are willing to use eval(parse(text=...)) :

如果您愿意使用eval(parse(text=…)):

 test.function <- function(x)  {
   z <- eval(parse( text=paste("df$", x, sep = "")), env=.GlobalEnv)
   return(z)
   }
test.function("A")
# [1]  1  2  3  4  5  6  7  8  9 10

BUT ... it is much better to use "[[". (My initial efforts at eval(parse()-ing were stuck at not knowing enough to use the "text" argument to parse.)

但是…最好使用"[]"。(我在eval(parse()-ing的最初工作是不知道如何使用“text”参数进行解析。)

#3


1  

In addition to eval(parse(text=YOUR_STRING)), you can use as.symbol as a potential alternative.

除了eval(parse(text=YOUR_STRING)),还可以使用as。符号作为一种潜在的选择。

#4


0  

You can create a variable name from a string using the assign operator, as in: assign("a_string", NULL)

您可以使用assign操作符从字符串中创建一个变量名,如:assign(“a_string”,NULL)