Hi @Brianboros7! You might benefit a little from doing some background reading on what functions are. This chapter from R For Data Science might help.
The object Hello
here is a function: a piece of code that does something. There are two things big parts of using functions: defining them and calling them.
What you're doing in your code is defining a function. You're describing what it'll do: when called, it'll take an input called name
and print out a greeting based on the value of name
, whether that value is "Brian"
or for "Sally"
or for "Irma"
. Importantly, all of those values have "quote marks" around them—that's how R can tell the difference between an object you've defined called Brian
and the value "Brian"
for something else, like name
.
Calling the function is the other part: that's when the function does what it says on the tin. I would call your first example like this:
Hello("Brian")
And when this happens, the value "Brian"
is assigned to the object name
, and the code inside the function is run.
But in your second example, you've changed (redefined) the function Hello
so that the function sprintf()
inside it (see how it's being called the same way?) is given an object called Brian
. There isn't any such object—there's only Hello
and name
—so an error happens.
If you changed your function like this:
another_hello <- function(name) {
sprintf("Hello, %S", Brian);
}
You could call it like sprintf("Irma")
or sprintf("Arnold")
, but it wouldn't matter what name
you gave it: because name
no longer appears inside the function, the value you input is no longer passed on to sprintf()
.
tl;dr:
- the first example is good, and you can call it using
Hello("Brian")
with quotes;
- the second example doesn't work because
"Brian"
is a value but Brian
is the name of an object that doesn't exist; and
- my third example doesn't cause an error, but it also doesn't work because the input isn't used properly.
I hope that helps!