Why am I getting this Error?

Hello a
I just started with R, and this "Hello, %S,", Brian is giving me an error and should be easy and given Hello, Brian output I'm being told via my MBA instructions. Confused.

Hello <- function( name ) {
      sprintf("Hello, %S", name);

That gives me no Error. but then this does.

Hello <- function( name ) {
      sprintf("Hello, %S", Brian);

Please give me your thoughts. I wish I could upload a screenshot but i don't see how. .

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:


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().


  • 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!

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.