53 thoughts on “swirl – R Programming – Lesson 9 – Functions”

  1. For some reason in telegram function paste(“START”, …, “STOP”, sep = ” “) was giving me an error: ” Remember that arguments can come after …”

    paste(“START”, …, “STOP”) worked just fine. Can’t figure out why.

    1. Hi Yana!

      Try copy and paste this as an R script. Run it, and see what you get?

      telegram <- function(...){
        paste("START", ..., "STOP", sep = " ")
      }
      
      telegram("Good", "morning")
      

      I got this in the console:

      > telegram <- function(...){
      +   paste("START", ..., "STOP", sep = " ")
      + }
      > telegram("Good", "morning")
      [1] "START Good morning STOP"
      

      Cheers,
      Johnny

      1. Hi,
        thanks a lot for the explanations. I was wondering why we need to add ‘ sep =” ” ‘ as the last argument here: paste(“START”,…,”STOP”, sep=” “) . Is that because of the rule that all arguments after the … need to be named ?

        One second question: if we replaced the … by an X , the outcome would be the same in this case. Why the need for the … ?

        thank you!!!!
        best
        Pedro

  2. Thanks for helping me get past a question that was taking too long to get right. For the madlibs function you wrote (and I wrote the same I think actually), how come it didn’t paste your input into the sentence? It seemed to have let you pass that section even though it didn’t work.

  3. Hi Denise. Great spot! I just realized I made a typo when invoking the mad_libs function! (The function is written correctly, but the calling of function contains one typo: the inpput adjustive should be corrected to adjective. i.e.

    This line:

    mad_libs(place = "London", adjustive = "beautiful", noun = "dog")
    

    will still run in RStudio (no idea why?). It will output an incorrect result (As it doesn’t know what adjustive is)

    [1] "News from London today where  students took to the streets in protest of the new dog being installed on campus."
    

    The calling of function should really be corrected to:

    mad_libs(place = "London", adjective = "beautiful", noun = "dog")
    

    which will output the correct expected result:

    [1] "News from London today where beautiful students took to the streets in protest of the new dog being installed on campus."
    

    Net net, it looks like the current mad_libs() function runs, regardless of whether an input is defined or not. If you / anyone can think of a simple (new or existing) way to make R throw up an error in the event of input not defined (e.g. in the case when adjective is mis-spelled as adjustive, please do share!

    (To block quote your code in this WordPress blog post comment, just add three back ticks above and below the code.)

    Thanks again Denise!

  4. Hi Johnny, I found that swirl is really helpful – thank you for that. I might need some help because I am stuck with my_mean for more than a day and the function I put in is exactly the same with yours here. I am not quite sure what causes the issue, I run it in R studio.

    1. Hi Rachel, thanks for the kind words. Sorry to hear you spent a day getting stuck on the my_mean problem! Try copy and paste the following in RStudio, what do you get?

      my_mean <- function(my_vector) {
        # Write your code here!
        # Remember: the last expression evaluated will be returned! 
        sum(my_vector) / length(my_vector)
      }
      
      my_mean(c(4, 5, 10))
      

      I get this:

      [1] 6.333333
      

      Good luck and do shout if you are still stuck!

      1. Hi Johnny,
        I am running into the same issue with the function my_mean as described by Rachel. I am unable to progress further even if I type the exact code. If copied your code into RStudio Console and got an error see below:

        my_mean <- function(my_vector) {
        + # Write your code here!
        + # Remember: the last expression evaluated will be returned!
        + sum(my_vector) / length(my_vector)
        + }

        my_mean(c(4, 5, 10))
        Error in sum(my_vector) : argument “y” is missing, with no default

        I am using R version 3.3.2 (2016-10-31) — “Sincere Pumpkin Patch”
        Copyright (C) 2016 The R Foundation for Statistical Computing
        Platform: x86_64-w64-mingw32/x64 (64-bit)

        Your assistance is appreciated.

        1. I was able to resolve the issue above. For some reason clearing the variables from the workspace in RStudio did the trick. Please note that restarting RStudio did not help remedy the error.

    1. Hi Mukul,

      Try running the following in RStudio, it should output what you would expect:

      "%p%" <- function(left, right){
        paste(left, right, sep = " ")
      }
      
      message = "I" %p% "love" %p% "R!"
      
      print(message)
      

      Output:

      [1] "I love R!"
      

      To get through the Swirl lesson, submit the function and invoke it like this at the console (type the following and hit enter):

      "I" %p% "love" %p% "R!"
      

      Hope this helps and do shout if you are still stuck!

      1. Thanks Johnny,its working.
        I discovered another way to solve this.

        “%p%” <- function(left, right){
        paste(left,right)
        }

  5. Hi Johnny

    I am stuck at evaluate assignment in lesson 9. Below is my code. Please help. Thanks.

    evaluate <- function(func, dat){

    dat<-c()
    func(dat)

    }

    Regards
    Vinit

    1. Have you tried this?

      evaluate <- function(func, dat){  
        func(dat)
      }
      

      Then call the function like this:

      evaluate(sum, c(2, 4, 6))
      evaluate(median, c(7, 40, 9))
      evaluate(floor, 11.1)
      

      You should get:

      > evaluate(sum, c(2, 4, 6))
      [1] 12
      > evaluate(median, c(7, 40, 9))
      [1] 9
      > evaluate(floor, 11.1)
      [1] 11
      

      Shout if you still get stuck!

      1. Keep getting the error – “Make sure that when you pass a function as an argument you pass the name of the function without parentheses!”

        I tried my syntax on R console and it works, but within swirl, it repeatedly gives me the above message.

        Please advise, how to get past this exercise.

  6. I believe the error was due to the incorrect order of “curly quotes” you used with the sep argument:
    you used: sep = ” “
    instead of: sep = “ ”
    better yet, always use straight quotes, to avoid these mistakes in the future
    like this: sep = ” “

  7. Hello Johnny,
    I’m having problems with the 15% assignment of this lesson (writting the first function). Do you know what’s wrong with the code? Thanks!

    You’re about to write your first function! Just like you would assign a value

    to a variable with the assignment operator, you assign functions in the following

    way:

    #

    function_name <- function(arg1, arg2){

    # # Manipulate arguments in some way
    # # Return a value

    }

    #

    The “variable name” you assign will become the name of your function. arg1 and

    arg2 represent the arguments of your function. You can manipulate the arguments

    you specify within the function. After sourcing the function, you can use the

    function by typing:

    function_name(value1, value2)

    #

    Below we will create a function called boring_function. This function takes

    the argument x as input, and returns the value of x without modifying it.

    Delete the pound sign in front of the x to make the function work! Be sure to

    save this script and type submit() in the console after you make your changes.

    boring_function <- function(x){
    x
    }

    submit()

    | Sourcing your script…

    | That’s not the answer I was looking for, but try again.

    | Make sure to delete the pound sign so the last expression in the function is just x.

    1. Hello, I recall when I did mine I only have the following lines in the code.

      boring_function <- function(x) {
        x
      }
      

      i.e. all the texts beginning with a pound sign # are just comments. Try replacing the entire code with just the above three lines. Does it work? (Good luck!)

  8. Hi Johnny,

    Thanks for your help. I am working my way through Swirl exercises as part of the Coursera R programming course. I am finding it a bit too challenging. I have been stuck for a few hours this afternoon on Swirl lesson 9 (“unpack” arguments).

    Here is the code I have written (which I believe matches yours):

    mad_libs <- function(…){
    # Do your argument unpacking here!
    args <- list(…)
    place <- args[[“place”]]
    adjective <- args[[“adjective”]]
    noun <- args[[“noun”]]
    # Don’t modify any code below this comment.
    # Notice the variables you’ll need to create in order for the code below to
    # be functional!
    paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
    }nxt
    

    Here is the error message I am getting:

    submit()
    
    | Sourcing your script…
    
    Error in source(e$script_temp_path) :
    C:\Users\Matthew\AppData\Local\Temp\RtmpshBSkp/mad_libs.R:40:2: unexpected symbol
    39: paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
    40: }nxt
    ^
    
    | Not exactly. Give it another go.
    
    | Your function should have three sections: capture the ellipsis in a list(), unpack the arguments from the ellipsis
    | and assign them to variables, then pass those variables to paste().
    

    I posted a question on the Coursera Swirl forum. The response I received was as follows: “Don’t subset args with character vectors. The function would only work that way if the input consisted of named values.”

    Any suggestions you have, would be greatly appreciated.

    1. Not sure if this was a copy and paste error. But I notice that you have this strange text at the end of your code. i.e.

      That last line:

      }nxt
      

      I believe should be just:

      }
      

      What do you think? Remove that nxt?

  9. Hi,

    I am in trouble to exit from vim. I typed “:quit!” but did not work. How to back to R?

    Thank you in advance for you help.

    Jin

    1. Hi Jin, i don’t use vim editor myself (but out of curiosity I decided to google it :). It appears that this StackOverflow Forum has the question and answer that you need. i.e. try :!q to quit without saving. Or :wq to “write (save) and quit”. (Seem to be fairly similar to the linux vi editor :) Also, are you using RStudio or just vanilla R? (Running Swirl in RStudio I guess might be easier?)

  10. Hi Johnny,

    First off, I am loving swirl! It is making R so much more fun. I am having trouble the with mad_libs section.

    My problem is you can erase all of the code beneath the function (except the paste function) and the function will still work if you specify what adjective, place, and noun are once you call it. I haven’t found a way to write this function so that I don’t need to specify what adjective, noun, and code are. The following two codes will produce the same result if each variable is specified. So how do write it such that we don’t have to specify what is stored in place, adjective, and noun?

    mad_libs <- function(…){
    # Do your argument unpacking here!
    args <- list(…)
    place <- args[[“place”]]
    adjective <- args[[“adjective”]]
    noun <- args[[“noun”]]
    # Don’t modify any code below this comment.
    # Notice the variables you’ll need to create in order for the code below to
    # be functional!
    paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
    }

    mad_libs(place = “champaign”, adjective = “migratory”, noun= “turnip”)
    [1] “News from champaign today where migratory students took to the streets in protest of the new turnip being installed on campus.”

    mad_libs(“champaign”, “migratory”, “turnip”)
    [1] “News from today where students took to the streets in protest of the new being installed on campus.”

    mad_libs <- function(…){
    # Do your argument unpacking here!
    # Don’t modify any code below this comment.
    # Notice the variables you’ll need to create in order for the code below to
    # be functional!
    paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
    }

    mad_libs(place = “champaign”, adjective = “migratory”, noun= “turnip”)
    [1] “News from champaign today where migratory students took to the streets in protest of the new turnip being installed on campus.”

  11. I reached 31% and I couldn’t understand reminder function.
    you replaced by to divisor don’t you ?
    What does mean %% in R ?

    best regards,

    1. Hey Norah, the %% is the Modulus operator (do a google search on “modulus operator”). Let me explain here anyway as it’s not really that difficult:

      Imagine, you have a basket of apples, shared among 3 people.

      • You use “division” (the / operator in R) to find out “how many apples do each per get evenly?”
      • You use “modulus” (the %% operator in R) to find out “how many apples remaining, once the apples have been shared out evenly?”.

      So, imagine you have different scenario (e.g. varying basket size):

      • 9 apples shared between 3 persons = 3 apples per person (with 0 apples remaining).
      • 8 apples shared between 3 persons = 2 apples per person (with 2 apples remaining).
      • 7 apples shared between 3 persons = 2 apples per person (with 1 apples remaining).
      • 6 apples shared between 3 persons = 2 apples per person (with 0 apples remaining).
      • 5 apples shared between 3 persons = 1 apple per person (with 2 apples remaining).
      • 4 apples shared between 3 persons = 1 apple per person (with 1 apples remaining).
      • 3 apples shared between 3 persons = 1 apple per person (with 0 apples remaining).
      • 2 apples shared between 3 persons = 0 apples per person (with 2 apples remaining).
      • 1 apple shared between 3 persons = 0 apple per person (with 1 apples remaining).
      • 0 apples shared between 3 persons = 0 apples per person (with 0 apples remaining).

      See the pattern?

      “X” number of apples shared between “Y” persons = “Z” apples per person (with R apples remaining”)

      Putting it in the “division” and “modulus” terms, we have:

      X (apples) / Y (persons) = Z (apples per person)

      X (apples) %% Y (persons) = R (apples remaining, once the apples have been shared evening between the Y persons).

      So (say “modulus” when you see the “%%”)

      X %% Y = R

      9 %% 3 = 0
      8 %% 3 = 2
      7 %% 3 = 1
      6 %% 3 = 0
      5 %% 3 = 2
      4 %% 3 = 1
      3 %% 3 = 0
      2 %% 3 = 2
      1 %% 3 = 1
      0 %% 3 = 0

      Notice the pattern? if Y = 3, there are 3 possibilities for R (0, 1, 2).

      This is the strength of modulus. In programming, whenever you are dealing with things involving with “cycles”, the modulus operator usually come in very handy. (You will know what I mean then! :)

      I hope this help. This is the best I can explain what modulus mean!

      Good luck!

    1. Hey, it works fine for me. Try restarting RConsole? i.e. in the Console of RStudio

      Restart console:

      .rs.restartR()
      

      Then compute mean:

      mean(c(2, 4, 5))
      

      Output:

      [1] 3.666667
      

      Hope this helps!

  12. Hi there!
    I have been stuck on madlibs function for a few hours! =( I tried copying and pasting from this site but to no avail. I keep getting the error message: object ‘place’ not found. Here the the code I’ve been using:

    mad_libs <- function(…){
    # Do your argument unpacking here!
    args <- list(…)
    place <- args[[“place”]]
    adjective <- args[[“adjective”]]
    noun <- args[[“noun”]]
    # Don’t modify any code below this comment.
    # Notice the variables you’ll need to create in order for the code below to
    # be functional!
    paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
    }

    1. Hey Steven,

      I’ve just had a go in my RStudio and managed to get it working. Try restarting the RConsole and start again. i.e.

      Step 1: submit this in RConsole directly (to clean up the session)

      .rs.restartR()
      

      Step 2: create a new file and save it (e.g. test.R)

      mad_libs <- function(...) {
        # Do your argument unpacking here!
        args <- list(...)
      
        place <- args[["place"]]
        adjective <- args[["adjective"]]
        noun <- args[["noun"]]
      
        # Don't modify any code below this comment.
        # Notice the variables you'll need to create in order for the code below to
        # be functional!
        paste("News from", place, "today where", adjective, "students took to the streets in protest of the new", noun, "being installed on campus.")
      
      }
      

      Step 3: highlight the code in step 2, click “run”. You should see the block of code is now processed in the RConsole.

      Step 4: invoke the mad_libs function in the RConsole like this:

      mad_libs(place = "London", adjective = "beautiful", noun = "dog")
      

      Output:

      [1] "News from London today where beautiful students took to the streets in protest of the new dog being installed on campus."
      

      Hope this helps!!! (sorry to hear that you’ve been stuck for hours – this chapter seems to be the one that most people get stuck on. It surprises me how this particular blog post has become so popular!!!)

      1. Thank you so much for your prompt response! One last question. I’m a novice at computer programming, and I am teaching myself R. I noticed that when going through the Swirl tutorial if I stop at a certain point and save, and then come back the next day to continue, I am unable to return to that same point. Meaning that today after starting R, I now have to start the entire Lesson 9 session from the beginning. Any suggestions?
        Thanks!

          1. what’s wrong with my code
            ?
            mad_libs <- function(…){

            args <- list(…)

            place <- args[[“place”]]
            adjective <- args[[“adjective”]]
            noun<- args[[“noun”]]

            paste(“News from”, place, “today where”, adjective, “students took to the streets in protest of the new”, noun, “being installed on campus.”)
            }

      2. submit()

        | Sourcing your script…

        Error in eval(expr, envir, enclos) : object ‘su’ not found

        | Nice try, but that’s not exactly what I was hoping for. Try again.

        | Your function should have three sections: capture the ellipsis in a list(), unpack the
        | arguments from the ellipsis and assign them to variables, then pass those variables to
        | paste().

        Hello Johnny,

        I am getting this error even after restarting R as u mentioned above.

  13. I got into an error when I got to this step

    | The last R expression to be evaluated in a function will become
    | the return value of that function. We want this function to take
    | one argument, x, and return x without modifying it. Delete the
    | pound sign so that x is returned without any modification. Make
    | sure to save your script before you type submit().

    Error in editor(file = file, title = title) :
    argument “name” is missing, with no default

    | Leaving swirl now. Type swirl() to resume.

    Am I missing something? Please help! Thanks!

    1. I’ve stuck with the same error, in RStudio Version 0.99.893, Windows 10.
      In R console the exercise is working fine, and a script window is opening.
      In RStudio it was working correctly on Windows8.1, 3 months ago.

        1. I found another way!
          I suppose, it does not working normally because version of my R 3.2.2
          I tried to install R 3.2.4 and swirl package on OS X and this package began to work fine!

  14. Write a function called remove_duplicates which will take one argument called string. This string input will only have characters between a-z.

    The function should remove all repeated characters in the string and return a tuple with two values:

    A new string with only unique, sorted characters.

    The total number of duplicates dropped.

Leave a reply