move_slow_break_things
move_slow_break_things

Reputation: 847

R- Use a string as an expression

I'll preface this by saying I know this is a slightly odd question to ask but I don't know how else to phrase it.

I have the following lines in a particular R script:

hist(sce$total_counts/1e6, xlab="Library sizes (millions)", main="", 
 breaks=20, col="grey80", ylab="Number of cells");

For this bit:

sce$total_counts/1e6

The 1e6 part should be an user input and I am trying to set it up so that the the first part and the user part get "concatenated" and then evaluated. Problem is using paste and other stuff returns strings and I don't want strings. I want to be able to swap out the "/1e6" part with "/1e3" for example and not change anything else about that line of code and still have it work. I tried to do the following:

object <- paste("sce$total_counts", args[1], sep="")
ob <- parse(text=object) # expression(sce$total_counts/1e6)
hist(ob, xlab="Library sizes (millions)", main="", 
 breaks=20, col="grey80", ylab="Number of cells");

But it returned this error:

Error in hist.default(ob, xlab = "Library sizes (millions)", main = "",  : 
  'x' must be numeric

I don't know how else to word it other than to say: How do you alias one part of the code as something else? I want ob with the user input of "/1e6" to mean the same as sce$total_counts/1e6

Upvotes: 0

Views: 76

Answers (1)

G. Grothendieck
G. Grothendieck

Reputation: 269371

If the idea is that you want to perform aribitrary transformations on the first argument of hist before performing the histogram then pass a function that does the transformation

myhist <- function(f, ...) {
  f <- match.fun(f)
  x <- 1:20
  hist(f(x, ...))
}

# test runs
myhist("/", 1e6)
myhist(function(x) x / 1e3)
f <- function(x) x / 100; myhist(f)
myhist(sqrt)

It would also be possible to pass a function in formula form like this. See ?fn:

library(gsubfn)
fn$myhist(~ x / 1e6)
fn$myhist(~ sqrt(x))

Upvotes: 2

Related Questions