Wednesday, 27 April 2016

R function: Use argument to extract data from other argument

Here is a simple R function:




aa <- function(x, cells, aberrations) {
return(list(x[[cells]], x[[aberrations]]))
}


So for example if I run this with sample data below, I have



df1 <- data.frame(x = 1:10, y = 11:20)
aa(df1, cells = "x", aberrations = "y")

[[1]]
[1] 1 2 3 4 5 6 7 8 9 10

[[2]]
[1] 11 12 13 14 15 16 17 18 19 20


Is there a way, I can extract the data from df1 with something like this?



aa(df1, cells = x, aberrations = y)



That is, not using a character, "x", but just x. I tried this,



aa <- function(x, cells, aberrations) {
a <- as.character(cells); b <- as.character(aberrations)
return(list(x[[a]], x[[as.character(b)]]))
}



But did not work.



This idea is inspired by the ggplot function, where I can do this,



ggplot(df1, aes(x, y)) + geom_point()


with no error at all even though x and y are not defined in the workspace, but on the data frame df1.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...