1## R Script Sample File 2## Source: http://www.rexamples.com 3 4## Basics 5a <- 42 6A <- a * 2 # R is case sensitive 7print(a) 8cat(A, "\n") # "84" is concatenated with "\n" 9if(A>a) # true, 84 > 42 10{ 11 cat(A, ">", a, "\n") 12} 13 14## Functions 15Square <- function(x) { 16 return(x^2) 17} 18 19print(Square(4)) 20print(Square(x=4)) # same thing 21 22DoSomething(color="red",number=55) 23 24## Countdown 25countdown <- function(from) 26{ 27 print(from) 28 while(from!=0) 29 { 30 Sys.sleep(1) 31 from <- from - 1 32 print(from) 33 } 34} 35 36countdown(5) 37 38## Reading user input 39readinteger <- function() 40{ 41 n <- readline(prompt="Enter an integer: ") 42 n <- as.integer(n) 43 if (is.na(n)){ 44 n <- readinteger() 45 } 46 return(n) 47} 48print(readinteger()) 49 50readinteger <- function() 51{ 52 n <- readline(prompt="Enter an integer: ") 53 if(!grepl("^[0-9]+$",n)) 54 { 55 return(readinteger()) 56 } 57 58 return(as.integer(n)) 59} 60print(readinteger()) 61 62## Guess a random number game 63readinteger <- function() 64{ 65 n <- readline(prompt="Enter an integer: ") 66 if(!grepl("^[0-9]+$",n)) 67 { 68 return(readinteger()) 69 } 70 return(as.integer(n)) 71} 72 73# real program start here 74 75num <- round(runif(1) * 100, digits = 0) 76guess <- -1 77 78cat("Guess a number between 0 and 100.\n") 79 80while(guess != num) 81{ 82 guess <- readinteger() 83 if (guess == num) 84 { 85 cat("Congratulations,", num, "is right.\n") 86 } 87 else if (guess < num) 88 { 89 cat("It's bigger!\n") 90 } 91 else if(guess > num) 92 { 93 cat("It's smaller!\n") 94 } 95} 96 97## Lists 98sum(0:9) 99append(LETTERS[1:13],letters[14:26]) 100c(1,6,4,9)*2 101something <- c(1,4,letters[2]) # indices start at one, you get (1,4,"b") 102length(something) 103 104## Pipe 105diamonds %>% 106 filter(price > 1000) %>% 107 group_by(cut) %>% 108 tally() %>% 109 rename(tally = n) %>% 110 arrange(-tally) %>% 111 mutate(pct = tally / sum(tally)) -> df 112 113## ggplot2 114plot = ggplot(diamonds, aes(x = price, y = carat)) + 115 geom_point(alpha = 0.3, colour = 'steelblue') + 116 labs( 117 title = "ggplot diamonds", 118 x = "Price, $", 119 y = "Carat" 120 ) + 121 facet_wrap(~ cut) + 122 theme_minimal() 123 124plot + coord_flip() 125