1. ######
  2. ## Abbrivations
  3.  
  4. len <- length
  5. f <- `function` #### DOESN'T WORK
  6.  
  7.  
  8. ######
  9. ## BASIC
  10.  
  11. ## If
  12. a <- 3
  13. if(a==3) print("is 3") else print("not 3")
  14.  
  15. ## For
  16. for(i in 1:10) print(i)
  17.  
  18.  
  19. #####
  20. ## Errors
  21.  
  22. ## Stop on error
  23. stop ("error happend")
  24.  
  25. ## null?
  26. is.null(NULL)
  27.  
  28.  
  29.  
  30. #####
  31. ## Data Structures
  32.  
  33. ## Vector
  34. num3to5 <- c(3,4,5)
  35. numTo10 <- 1:10
  36.  
  37. ## Matrix
  38. ones <- rep(1,times=9)
  39. m1 <- matrix(ones, nrow=3, ncol=3, byrow = FALSE)
  40.  
  41. ## number of rows
  42. nrow(m1)
  43.  
  44.  
  45. ## List of matrices
  46. matrices <- list(m1, m1, m1)
  47. firstm <- matrices[[1]]
  48.  
  49.  
  50.  
  51. #####
  52. ## MISC
  53.  
  54. ## sum, max,
  55. sum(1:10)
  56. max(1:10)
  57.  
  58. ## String
  59. paste("a", "b")
  60. cat(c(1,2))
  61.  
  62.  
  63. ####
  64. ## MATH MISC
  65.  
  66. ## transpose matrix
  67. t(m1)
  68.  
  69. ## random sample
  70. sample(1:10, 1)
  71.  
  72.  
  73.  
  74. ## Apply
  75.  
  76. ## List (of matrices)
  77.  
  78.  
  79.  
  80.  
  81. ######
  82. ## HIGH LEVEL FUNCTIONS
  83.  
  84.  
  85. ## apply
  86. apply(statex77, 2, median) # 2:bycolumn 1:byrow
  87.  
  88. ## apply2
  89. m <- matrix(c(1:10, 11:20), nrow = 10, ncol = 2)
  90. # divide all values by 2
  91. apply(m, 1:2, function(x) x/2)
  92.  
  93. ## which
  94. which(1:10 == 3)
  95.  
  96. ## Filter
  97. gr3 <- function(x) if(x>3) return(TRUE) else return(FALSE)
  98. num4to10 <- Filter(gr3, 1:10)
  99.  
  100. ## Map
  101. nums <- unlist( Map(sqrt, 1:10) )
  102.  
  103. ## Map - Reduce
  104. nums_string <- Reduce(paste, Map(sqrt, 1:10) )
  105.  
  106.  
  107. ## mapply
  108.  
  109.  
  110. ## sapply (simple)
  111. sapply(3:5, function(i)i+1)
  112.  
  113.  
  114. ## lapply (list)
  115.  
  116. ## reading numbers
  117.  
  118. ## further apply stuff:
  119. ### http://nsaunders.wordpress.com/2010/08/20/a-brief-introduction-to-apply-in-r/
  120.  
  121.