How to convert a string in a function into an object?

前端 未结 5 843
你的背包
你的背包 2020-12-14 17:55

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 =         


        
5条回答
  •  天涯浪人
    2020-12-14 18:56

    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".

    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:

     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=...)) :

     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.)

提交回复
热议问题