0

I am attempting to create a function, which would make me easily plot data by a given year from dataframe with data for many years. I have succeeded in doing this. However, I also want the given year to be shown in the title, but can't figure out how to put an argument into the title string.

For simplicity, I will just show a mock function:

my_plot <- function(x){
v1 <- x:10
return(plot(v1, main = "The year of ...y..."))
}
my_plot(x=4)

enter image description here

How do I replace ...y... with an function argument?

Best, Rikki

4
  • 1
    FYI plot() plots as a side effect, your function is in fact always returning NULL Commented Oct 18, 2022 at 11:56
  • The graph was made using the given mock function, so I guess it is not returning NULL? Commented Oct 18, 2022 at 12:04
  • It is plotting, but it does return NULL, try foo <- my_plot(x=4);foo Commented Oct 18, 2022 at 12:19
  • your return() call doesn't hurt but it's a bit misleading, since your function is only called for side effects. I understand this can be confusing, for example ggplot produces real plot objects that you can store in variables. bas exploiting is not like that Commented Oct 18, 2022 at 12:20

1 Answer 1

1

You can use paste() to combine two different strings:

my_plot <- function(x, year){
v1 <- x:10
return(plot(v1, main = paste("The year of", year))
}
my_plot(x=4)
Sign up to request clarification or add additional context in comments.

3 Comments

sep doesn't seem needed here. paste() is a good way to do it, I also like sprintf("The year of &s", year), and then there's also glue::glue("The year of {year}")
Thank you so much guys! I had completely forgotten about the paste function.
@moodymudskipper Right, that was a mistake, idk why I added a comma. Thanks!

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.