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
  • 20,087
  • 21
  • 101
  • 151

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
  • 184,536
  • 28
  • 389
  • 466