Reputation: 1854
I am trying to make a function that takes in a dataframe and adds a new variable which is the name of the input dataframe. For example:
foo <- data.frame(x = 1:10, y = rep(c("a", "b")))
mutate(foo, id = "foo")
This seemed relatively trivial to accomplish, since this works as it does here:
var_as_string <- function(x) {deparse(substitute(x))}
var_as_string(foo)
Result:
[1] "foo"
I figured this would as well, but it doesn't:
add_id <- function(x) {
mutate(x, id = deparse(substitute(x)))
}
add_id(foo)
Result:
zz yy id
1 1 a x
2 2 b x
3 3 a x
4 4 b x
5 5 a x
6 6 b x
7 7 a x
8 8 b x
9 9 a x
10 10 b x
As a test, I tried this and it doesn't work as I thought it would either:
var_as_string2 <- function(x) {
var_string <- var_as_string(x)
var_string(x)
}
var_as_string2(foo)
Result:
[1] "x"
Is there a solution to this? Am I overlooking something here or do I have a fundamental misunderstanding of functions in R?
Upvotes: 4
Views: 1975
Reputation: 14346
There is probably a better 1-line way of achieving this using lazyeval
but this seems to work
add_id <- function(x) {
s <- as.character(substitute(x))
mutate(x, id = s)
}
add_id(foo)
(the idea compared to what you were trying to do is that you have to evaluate s
outside the mutate
call)
Upvotes: 3