# swirl – R Programming – Lesson 9 – Functions

## 61 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. Johnny says:

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. pedro says:

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. Denise says:

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. Johnny says:

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. Rachel says:

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. Johnny Chan says:

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) {
# 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. wm says:

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)

1. wm says:

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.

2. Ben Karmay says:

Seems I’m having the same problem as Rachel. I’m really out of ideas and tried many many variations. Is this close to what I am meant to be doing?

my_mean <- function(my_vector) {
+ sum(my_vector)/length(my_vector)
+ }
my_mean
function(my_vector) {
sum(my_vector)/length(my_vector)
}
my_mean(c(4, 5, 10))
[1] 6.333333
submit()

| That’s not exactly what I’m looking for. Try again.

| Use the sum() function to find the sum of all the numbers in the
| vector. Use the length() function to find the size of the vector.

1. Katherine says:

Hi, did you solve this problem?
I’m facing the same problem now.
Thanks a lot

5. mukul says:

Hi John I need some help because I am stuck with “%p%” which is creating a binary operator.

1. Johnny says:

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. mukul says:

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

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

6. Hi Johnny

evaluate <- function(func, dat){

 dat<-c() func(dat) 

}

Regards
Vinit

1. Johnny says:

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. guru says:

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.

7. Kirill says:

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 = ” “

8. Anonymous says:

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

| 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. Johnny says:

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

1. Anonymous says:

It worked, thanks a lot!

1. Johnny says:

2. SINDHU says:

I used the same code. It is showing error and is asking to remove pound sign.

3. Anonymous says:

Thanks it works

4. Hi Johnny,
Thanks for your disposition to help. I’m having the same issue and even though I’m trying what you suggested, it still doesn’t work for me:

1 | boring_function <- function(x) {
2 | x
3 | }

submit()

| You’re close…I can feel it! Try it again.

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

Could you give me some suggestion, please? Thanks very much!

9. Matthew Ingmire says:

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”]]
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()

Error in source(e\$script_temp_path) :
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. Johnny says:

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?

10. Jin says:

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. Johnny says:

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?)

2. OusmaneBarra says:

In order do that on the keyboard : ECHAP, : , wq!

11. Stephen says:

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?

# Do your argument unpacking here!
args <- list(…)
place <- args[[“place”]]
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] “News from champaign today where migratory students took to the streets in protest of the new turnip being installed on campus.”

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

# 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.”)
}

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

12. 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. oh it is the most difficult tutorial.
Could you recommend me lessons in function ?

2. Johnny says:

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!

13. What is wrong with the below command?

mean(c(2, 4, 5))

Error in mean(c(2, 4, 5)) : argument “cols” is missing, with no default

1. Johnny says:

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!

14. Steven says:

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:

# Do your argument unpacking here!
args <- list(…)
place <- args[[“place”]]
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. Johnny says:

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"]]
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. Anonymous says:

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. Steven says:

btw the above question is from Steve, I posted the question on MadLibs last night (Feb 16). Thanks

1. Anonymous says:

what’s wrong with my code
?

args <- list(…)

place <- args[[“place”]]
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.”)
}

1. Anonymous says:

TAT!I have the same problem, have you solved it?

2. Anonymous says:

submit()

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

3. EIrc says:

Hi Johnny,

nice to see your work, but i have a problem coming to the function “evaluate” ” func(data)”
i submit the same answer as you did, but it always return as follow

| Make sure that when you pass a function as an argument you pass the name of the function without parentheses!

don’t know if you are still working on this blog, it would be luck if you reply

15. 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.

1. Tseo says:

the same problem… do you solve it?

2. Andrew says:

I got exactly that error too

1. Tseo says:

maybe windows7? I have reintall swirl and the same error.. I cant continue..

3. Krzychu says:

i’ve got the same error! please, help

4. Милко Николаев Копаранов says:

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. Andrew says:

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!

2. Tried the method in the link and it worked! Thanks!

16. Tseo says:

Thank you!

17. mario says:

i am now in

18. Anonymous says:

how armstrong numbers are written in R programming?

19. Omotola Owoseni says:

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.

20. Sandra says:

Hi Johnny

I’m stuck in the exercise evaluate (function)
The first exercise said: try using evaluate() along with an anonymous function to return the first element of the vector c(8, 4, 0). Your anonymous function should only take one argument which should be a variable x

To do that exercise I did evaluate (function (x) {x [1]}, c (8,4,0))
and it was ok

But in the next exercise that I think is exactly the same than the first one: “Now try using evaluate() along with an anonymous function to return the last element of the vector c(8, 4, 0). Your anonymous function should only take one argument which should be a variable x“. I did:
evaluate (function (x) {x [3]}, c (8,4,0)), but here swirl told me that:
You’re close…I can feel it! Try it again. Or, type info() for more options.

| You may need to recall how to index vector elements. Remember that your anonymous function should only have one
| argument, and that argument should be named x. Using the length() function in your anonymous function may help
| you.

so I tried with every option possible
1) evaluate (function (x) {x [3]}, length (c (8, 4, 0)))
2) evaluate (function (x) {x[3]; length (c(8,4,0))}, c(8,4,0))
3) evaluate (function (x) {x [3]; c (8, 4, 0)}, length (c(8,4.0)))
and neither of them are correct, appears a note that said “is not exactly what is looking for… try again” in each case

Can you help me with that because I do not know another way to write the function
Thanks

1. Johnny says:

Hi Sandra sorry for the VERY DELAYED response! Just wondering if you’ve managed to solve this issue? (I haven’t touched R for a little while but if you are still stuck I could possibly give this a go. Let me know! :)

21. Joy Oliver says:

| Now try using evaluate() along with an anonymous function to return the last element
| of the vector c(8, 4, 0). Your anonymous function should only take one argument which
| should be a variable x.

Why isn’t:
evaluate(function(x) {x[3]}, c(8, 4, 0))
correct?
I don’t understand why
evaluate(function(x){x[length(x)]}, c(8, 4, 0))
is correct when they both return the correct answer, and the former is shorter in text.