Advertisement
Guest User

script

a guest
Nov 26th, 2015
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.90 KB | None | 0 0
  1. # FUNCTIONS --
  2. square <- function(x) {
  3.   return(x*x)
  4. }
  5. cat("The square of 3 is ", square(3), "\n")
  6.  
  7.                  # default value of the arg is set to 5.
  8. cube <- function(x=5) {
  9.   return(x*x*x);
  10. }
  11. cat("Calling cube with 2 : ", cube(2), "\n")    # will give 2^3
  12. cat("Calling cube        : ", cube(), "\n")     # will default to 5^3.
  13.  
  14. # LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
  15. powers <- function(x) {
  16.   parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
  17.   return(parcel);
  18. }
  19.  
  20. X = powers(3);
  21. print("Showing powers of 3 --"); print(X);
  22.  
  23. # WRITING THIS COMPACTLY (4 lines instead of 7)
  24.  
  25. powerful <- function(x) {
  26.   return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
  27. }
  28. print("Showing powers of 3 --"); print(powerful(3));
  29.  
  30. # In R, the last expression in a function is, by default, what is
  31. # returned. So you could equally just say:
  32. powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement