fork download
  1. # Goals: To write functions
  2. # To write functions that send back multiple objects.
  3.  
  4. # FIRST LEARN ABOUT LISTS --
  5. X = list(height=5.4, weight=54)
  6. print("Use default printing --")
  7. print(X)
  8. print("Accessing individual elements --")
  9. cat("Your height is ", X$height, " and your weight is ", X$weight, "\n")
  10.  
  11. # FUNCTIONS --
  12. square <- function(x) {
  13. return(x*x)
  14. }
  15. cat("The square of 3 is ", square(3), "\n")
  16.  
  17. # default value of the arg is set to 5.
  18. cube <- function(x=5) {
  19. return(x*x*x);
  20. }
  21. cat("Calling cube with 2 : ", cube(2), "\n") # will give 2^3
  22. cat("Calling cube : ", cube(), "\n") # will default to 5^3.
  23.  
  24. # LEARN ABOUT FUNCTIONS THAT RETURN MULTIPLE OBJECTS --
  25. powers <- function(x) {
  26. parcel = list(x2=x*x, x3=x*x*x, x4=x*x*x*x);
  27. return(parcel);
  28. }
  29.  
  30. X = powers(3);
  31. print("Showing powers of 3 --"); print(X);
  32.  
  33. # WRITING THIS COMPACTLY (4 lines instead of 7)
  34.  
  35. powerful <- function(x) {
  36. return(list(x2=x*x, x3=x*x*x, x4=x*x*x*x));
  37. }
  38. print("Showing powers of 3 --"); print(powerful(3));
  39.  
  40. # In R, the last expression in a function is, by default, what is
  41. # returned. So you could equally just say:
  42. powerful <- function(x) {list(x2=x*x, x3=x*x*x, x4=x*x*x*x)}
  43.  
Success #stdin #stdout 0.3s 22840KB
stdin
Standard input is empty
stdout
[1] "Use default printing --"
$height
[1] 5.4

$weight
[1] 54

[1] "Accessing individual elements --"
Your height is  5.4  and your weight is  54 
The square of 3 is  9 
Calling cube with 2 :  8 
Calling cube        :  125 
[1] "Showing powers of 3 --"
$x2
[1] 9

$x3
[1] 27

$x4
[1] 81

[1] "Showing powers of 3 --"
$x2
[1] 9

$x3
[1] 27

$x4
[1] 81