renozao / FAQR

Frequently Asked Questions on R: my personal Ask Just Once system for my friends' R problems...
0 stars 0 forks source link

Converting a value of a variable to a variable #11

Open Rachelly opened 9 years ago

Rachelly commented 9 years ago

I sometime need to use the value of a variable as a variable of its own, and don't know how to convert it... For example when I want to draw a plot using the following code: ggplot(DF, aes(Disease, GeneOrPW, fill = Type)) + ...

Where DF is a data.frame that contains the columns "Disease", "Type", "PW_corr" and "Gene_corr" GeneOrPW is a variable that either contains the string "PW_corr" or "Gene_corr".

The error I currently get when trying to run the ggplot code is: Error in eval(expr, envir, enclos) : object 'GeneOrPW' not found

I tried to change it to: ggplot(DF_merged, aes(Disease, eval(parse(GeneOrPW)), fill = Type)) + And got the error: Error in parse(GeneOrPW) : object 'GeneOrPW' not found

Thanks!

azk commented 9 years ago

Hi,

Instead of using aes, use aes_string which is a good fit for this situation:

ggplot(DF, aes_string("Disease", GeneOrPW, fill = "Type")) + ...

renozao commented 9 years ago

Wondering if Amit's suggestion work. Is GeneOrPW a variable in the data.frame, with length > 1?

Rachelly commented 9 years ago

It did work! Thanks Amit :-) GeneOrPW is a variable seperated from the data.frame. It a parameter of a function that contains one of 2 column names of the data.frame.