Evaluate dataframe$column expression stored as a string value

后端 未结 2 589
轻奢々
轻奢々 2021-01-28 22:11

Can a string of the form below be evaluated so that it is equivalent to the same \"literal\" expression?

Example data and code:

df.name = data.frame(col1         


        
相关标签:
2条回答
  • 2021-01-28 22:29

    You are almost there:

    > eval(parse(text = var1))
    [1] "D"
    

    Because parse expecting file by default, you need to specify the text parameter.

    0 讨论(0)
  • 2021-01-28 22:33

    I'm trying to create a function that will search (subset) df.name using the col.name passed to the function.

    Set up data:

    df.name = data.frame(col1 = 1:5, col2 = LETTERS[1:5], ## seq() is unnecessary
                         col3 = letters[1:5], 
                         stringsAsFactors = FALSE)
    col.name = "col2"
    row.num = "4"
    

    Solving your ultimate (index the data frame by column name) rather than your proximal (figure out how to use get()/eval() etc.) question: as @RichardScriven points out,

    f <- function(col.name,row.num,data=df.name)
       return(data[[col.name]][as.numeric(row.num)])
    }
    

    should work. It would probably be more idiomatic if you specified the row number as numeric rather than character, if possible ...

    0 讨论(0)
提交回复
热议问题