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');

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

4 Comments

To be fair... the explicit print makes sense in a function called 'printdf'
@Dason, I guess so. But doesn't that interfere with, for example head?
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?"
The recent edit isn't in line with the output given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.