1

I have a function that takes a data frame as an argument. In that function I need to use if/else construct to do some actions based on the data frame used as argument. for example, I need to be able to say

if (name of data frame=="Anthro_Data") {do this} else if (the name of data frame=="Sports") {do that}.

The problem I am having is that I don't know how to get the name of the data frame (as a string) in order to use it. Any suggestions!

BICube
  • 4,451
  • 1
  • 23
  • 44
  • This seems like a very odd way to define a function. Since who is calling the function knows where the data.frame came from (in theory) shouldn't you just call different functions depending on the contents of the data.frame rather than hard coding a particular variable name in a function? – MrFlick Jul 17 '14 at 21:47
  • @ MrFlick, Thanks for the comment. The task for my function is to do some aggregation and return an aggregated data frame. my data frames have different dimensions/column names so I either use your approach or my approach. I am not an experienced programmer and don't know the best practice but this seemed like a solution to me. I thought it would be just less confusing to call one function on my five data frames rather than sourcing and calling 5 functions with different names that will eventually do the same task. – BICube Jul 17 '14 at 22:04
  • If you want to do different things based on what's passed in, I would suggest doing things like looking at the column names (if that's what's important to you). That's more flexible than requiring a particular variable name to be passed in. – MrFlick Jul 17 '14 at 22:06
  • @MrFlick thank you so much for commenting on this. – BICube Jul 17 '14 at 22:09

1 Answers1

3

You can use deparse and substitute to get the name of the argument passed to your function:

a <- 1
f <- function(arg) deparse(substitute(arg))
f(a)
# [1] "a"
josliber
  • 43,891
  • 12
  • 98
  • 133
  • ...I was only going to add as an aside that I would probably prefer to do this using an attribute on the data frame, rather than deparsing the name. – joran Jul 17 '14 at 21:46
  • thanks @joran for the other suggestion – BICube Jul 17 '14 at 22:06