简体   繁体   中英

Incorporating user input in factor function in R

I am trying to figure out how to take a column name supplied by a user in response to a prompt in R and use that in the function factor. The idea is to create a script using ggplot2 that will allow users to easily select which variable from a table they would like coded by color and which by shape.
The line of code requesting user input would be:

> Color_Factor<-readline("What is the Column Heading of the Variable you would like separated by Color? ") 

What is the Column Heading of the Variable you would like separated by Color? Reach

My problem is that I can't figure out how to use this input to call a particular column for graphing purposes. The code below creates a graph with one color and the single variable "Reach".

> qplot(d13C, d15N, data=InputFile, **col=factor(Color_Factor)**, shape=factor(Functional_Group))

All my attempts at calling a function as the initial argument in factor() have met with complete failure. I'm specifically interested in this for graphing purposes but am also wondering if there is a way to use the value of a variable rather than the variable name to specify a column in this type of function in general. I'm totally new to R so maybe there's an obvious solution but I haven't been able to find an answer online so far. Thanks

This isn't very elegant but the non-standard evaluation of arguments to ggplot2 has always confused the heck out of me:

> Color_Factor<-readline("What is the Column Heading of the Variable you would like separated by Color? ") 
What is the Column Heading of the Variable you would like separated by Color? mpg

qplot( x=mtcars[, Color_Factor], wt, data=mtcars)

I've tried (and failed with) a variety of language level incantations using as.name , substitute , and eval to supply the x-argument with a language element that satisfied it. The strategy above uses the capacity of [.data.frame to evaluate the Color_Factor and match it to a column name in mtcars . This alternative also succeeds (since it is pretty much duplicating what the first one is doing:

 qplot( x=eval(as.name(Color_Factor), mtcars), wt, data=mtcars)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM