4

I pass data frame name as string into a function. How do I get content of referenced data frame from the string? Suppose I have string 'mtcars' and I want to print data frame mtcars:

printdf <- function(dataframe) {
  print(dataframe)
}

printdf('mtcars');
Tomas Greif
  • 21,685
  • 23
  • 106
  • 155

1 Answers1

5

I think you'll need a get in there if the input is a string. Also, depending on your usage of the function, the explicit print might not be necessary:

printdf <- function(dataframe) {
  get(dataframe)
  # print(get(dataframe))
}
head(printdf("mtcars"))
#                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
# Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
# Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1
A5C1D2H2I1M1N2O1R2T1
  • 190,393
  • 28
  • 405
  • 485
  • To be fair... the explicit print makes sense in a function called 'printdf' – Dason Dec 10 '13 at 15:36
  • @Dason, I guess so. But doesn't that interfere with, for example `head`? – A5C1D2H2I1M1N2O1R2T1 Dec 10 '13 at 15:37
  • Depends on what the goal is. I could imagine being frustrated if I wrote a function like this: `blah <- function(df){printdf(df); print("That was my dataframe")}; blah("mtcars")` and if printdf was defined your way I might initially be like "y u no print?" – Dason Dec 10 '13 at 15:40
  • 1
    The recent edit isn't in line with the output given. – Dason Dec 10 '13 at 15:46