├── .gitattributes ├── Chapter 1 Conditionals and Control Flow.R ├── Chapter 2 Loops.R ├── Chapter 3 Functions.R ├── Chapter 4 The Apply Family.R └── Chapter 5 Utilities.R /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto -------------------------------------------------------------------------------- /Chapter 1 Conditionals and Control Flow.R: -------------------------------------------------------------------------------- 1 | ###Chapter 1 Conditionals And Control Flow 2 | 3 | ###Equality 4 | # Comparison of logicals 5 | TRUE == FALSE 6 | 7 | # Comparison of numerics 8 | -6 * 14 != 17 - 101 9 | 10 | # Comparison of character strings 11 | "useR" == "user" 12 | 13 | # Compare a logical with a numeric 14 | TRUE == 1 15 | 16 | ###Greater And Less Than 17 | # Comparison of numerics 18 | -6*5+2 >= -10+1 19 | 20 | # Comparison of character strings 21 | "raining" <= "raining dogs" 22 | 23 | # Comparison of logicals 24 | TRUE > FALSE 25 | 26 | ###Compare Vectors 27 | # The linkedin and facebook vectors have already been created for you 28 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 29 | facebook <- c(17, 7, 5, 16, 8, 13, 14) 30 | 31 | # Popular days 32 | linkedin > 15 33 | 34 | # Quiet days 35 | linkedin <= 5 36 | 37 | # LinkedIn more popular than Facebook 38 | linkedin > facebook 39 | 40 | ###Compare Matrices 41 | # The social data has been created for you 42 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 43 | facebook <- c(17, 7, 5, 16, 8, 13, 14) 44 | views <- matrix(c(linkedin, facebook), nrow = 2, byrow = TRUE) 45 | 46 | # When does views equal 13? 47 | views == 13 48 | 49 | # When is views less than or equal to 14? 50 | views <= 14 51 | 52 | # How often does facebook equal or exceed linkedin times two? 53 | sum(facebook >= linkedin * 2) 54 | 55 | ###& And | 56 | # The linkedin and last variable are already defined for you 57 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 58 | last <- tail(linkedin, 1) 59 | 60 | # Is last under 5 or above 10? 61 | last<5 | last>10 62 | 63 | # Is last between 15 (exclusive) and 20 (inclusive)? 64 | last>15 & last<=20 65 | 66 | # Is last between 0 and 5 or between 10 and 15? 67 | (last > 0 & last < 5) | (last > 10 & last < 15) 68 | 69 | ###& And | (2) 70 | # The social data (linkedin, facebook, views) has been created for you 71 | 72 | # linkedin exceeds 10 but facebook below 10 73 | linkedin>10 & facebook<10 74 | 75 | # When were one or both visited at least 12 times? 76 | linkedin>=12 | facebook>=12 77 | 78 | # When is views between 11 (exclusive) and 14 (inclusive)? 79 | views>11 & views<=14 80 | 81 | ###Reverse The Result: ! 82 | x <- 5 83 | y <- 7 84 | !(!(x < 4) & !!!(y > 12)) 85 | 86 | ###Blend It All Together 87 | # li_df is pre-loaded in Data Camp's workspace 88 | 89 | # Select the second column, named day2, from li_df: second 90 | second <- li_df$day2 91 | 92 | # Build a logical vector, TRUE if value in second is extreme: extremes 93 | extremes <- second > 25 | second < 5 94 | 95 | # Count the number of TRUEs in extremes 96 | sum(extremes) 97 | 98 | # Solve it with a one-liner 99 | sum(li_df$day2 > 25 | li_df$day2 < 5) 100 | 101 | ###The If Statement 102 | # Variables related to your last day of recordings 103 | medium <- "LinkedIn" 104 | num_views <- 14 105 | 106 | # Examine the if statement for medium 107 | if (medium == "LinkedIn") { 108 | print("Showing LinkedIn information") 109 | } 110 | 111 | # Write the if statement for num_views 112 | if (num_views>15) { 113 | print("You're popular!") 114 | } 115 | 116 | ###Add An Else 117 | # Variables related to your last day of recordings 118 | medium <- "LinkedIn" 119 | num_views <- 14 120 | 121 | # Control structure for medium 122 | if (medium == "LinkedIn") { 123 | print("Showing LinkedIn information") 124 | } else { 125 | print("Unknown medium") 126 | } 127 | 128 | # Control structure for num_views 129 | if (num_views > 15) { 130 | print("You're popular!") 131 | } else { 132 | print("Try to be more visible!") 133 | } 134 | 135 | ###Customize Further: Else If 136 | # Variables related to your last day of recordings 137 | medium <- "LinkedIn" 138 | num_views <- 14 139 | 140 | # Control structure for medium 141 | if (medium == "LinkedIn") { 142 | print("Showing LinkedIn information") 143 | } else if (medium == "Facebook") { 144 | print("Showing Facebook information") 145 | } else { 146 | print("Unknown medium") 147 | } 148 | 149 | # Control structure for num_views 150 | if (num_views > 15) { 151 | print("You're popular!") 152 | } else if (num_views <= 15 & num_views > 10) { 153 | print("Your number of views is average") 154 | } else { 155 | print("Try to be more visible!") 156 | } 157 | 158 | ###Else If 2.0 159 | #1. 160 | number <- 6 161 | #2. 162 | number <- 100 163 | #3. 164 | number <- 4 165 | #4. 166 | number <- 2500 167 | if (number < 10) { 168 | if (number < 5) { 169 | result <- "extra small" 170 | } else { 171 | result <- "small" 172 | } 173 | } else if (number < 100) { 174 | result <- "medium" 175 | } else { 176 | result <- "large" 177 | } 178 | print(result) 179 | 180 | ###Take Control! 181 | # Variables related to your last day of recordings 182 | li <- 15 183 | fb <- 9 184 | 185 | # Code the control-flow construct 186 | if (li >= 15 & fb >= 15) { 187 | sms <- 2 * (li + fb) 188 | } else if (li < 10 & fb < 10) { 189 | sms <- 0.5 * (li + fb) 190 | } else { 191 | sms <- li + fb 192 | } 193 | 194 | # Print the resulting sms to the console 195 | print(sms) 196 | -------------------------------------------------------------------------------- /Chapter 2 Loops.R: -------------------------------------------------------------------------------- 1 | ###Chapter 2 Loops 2 | 3 | ###Write A While Loop 4 | # Initialize the speed variable 5 | speed <- 64 6 | 7 | # Code the while loop 8 | while (speed>30) { 9 | print("Slow down!") 10 | speed <- speed - 7 11 | } 12 | 13 | # Print out the speed variable 14 | speed 15 | 16 | ###Throw In More Conditionals 17 | # Initialize the speed variable 18 | speed <- 64 19 | 20 | # Extend/adapt the while loop 21 | while (speed > 30) { 22 | print(paste("Your speed is",speed)) 23 | if (speed > 48) { 24 | print("Slow down big time!") 25 | speed <- speed - 11 26 | } else { 27 | print("Slow down!") 28 | speed <- speed - 6 29 | } 30 | } 31 | 32 | ###Stop The While Loop: Break 33 | # Initialize the speed variable 34 | speed <- 88 35 | 36 | while (speed > 30) { 37 | print(paste("Your speed is",speed)) 38 | 39 | # Break the while loop when speed exceeds 80 40 | if (speed > 80) 41 | break 42 | 43 | if (speed > 48) { 44 | print("Slow down big time!") 45 | speed <- speed - 11 46 | } else { 47 | print("Slow down!") 48 | speed <- speed - 6 49 | } 50 | } 51 | 52 | ###Build A While Loop From Scratch 53 | # Initialize i as 1 54 | i <- 1 55 | 56 | # Code the while loop 57 | while (i <= 10) { 58 | print(i * 3) 59 | if ( (i * 3) %% 8 == 0) { 60 | break 61 | } 62 | i <- i + 1 63 | } 64 | 65 | ###Loop Over A Vector 66 | # The linkedin vector has already been defined for you 67 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 68 | 69 | # Loop version 1 70 | for (p in linkedin) { 71 | print(p) 72 | } 73 | 74 | # Loop version 2 75 | for (i in 1:length(linkedin)) { 76 | print(linkedin[i]) 77 | } 78 | 79 | ###Loop Over A List 80 | # The nyc list is already specified 81 | nyc <- list(pop = 8405837, 82 | boroughs = c("Manhattan", "Bronx", "Brooklyn", "Queens", "Staten Island"), 83 | capital = FALSE) 84 | 85 | # Loop version 1 86 | for (info in nyc) { 87 | print(info) 88 | } 89 | 90 | # Loop version 2 91 | for (i in 1:length(nyc)) { 92 | print(nyc[[i]]) 93 | } 94 | 95 | ###Loop Over A Matrix 96 | # The tic-tac-toe matrix has already been defined for you 97 | ttt <- matrix(c("O", NA, "X", NA, "O", NA, "X", "O", "X"), nrow = 3, ncol = 3) 98 | 99 | # define the double for loop 100 | for (i in 1:nrow(ttt)) { 101 | for (j in 1:ncol(ttt)) { 102 | print(paste("On row", i, "and column", j, "the board contains", ttt[i,j])) 103 | } 104 | } 105 | 106 | ###Mix It Up With Control Flow 107 | # The linkedin vector has already been defined for you 108 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 109 | 110 | # Code the for loop with conditionals 111 | for (li in linkedin) { 112 | if (li > 10) { 113 | print("You're popular!") 114 | } else { 115 | print("Be more visible!") 116 | } 117 | print(li) 118 | } 119 | 120 | ###Next, You Break It 121 | # The linkedin vector has already been defined for you 122 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 123 | 124 | # Adapt/extend the for loop 125 | for (li in linkedin) { 126 | if (li > 10) { 127 | print("You're popular!") 128 | } else { 129 | print("Be more visible!") 130 | } 131 | 132 | # Add code to conditionally break iteration 133 | if (li > 16) { 134 | print("This is ridiculous, I'm outta here!") 135 | break 136 | } 137 | 138 | # Add code to conditionally skip iteration 139 | if (li < 5) { 140 | print("This is too embarrassing!") 141 | next 142 | } 143 | 144 | print(li) 145 | } 146 | 147 | ###Build A For Loop From Scratch 148 | # Pre-defined variables 149 | rquote <- "r's internals are irrefutably intriguing" 150 | chars <- strsplit(rquote, split = "")[[1]] 151 | 152 | # Initialize rcount 153 | rcount <- 0 154 | 155 | # Finish the for loop 156 | for (char in chars) { 157 | if (char == "r") { 158 | rcount <- rcount + 1 159 | } 160 | if (char == "u") { 161 | break 162 | } 163 | } 164 | 165 | # Print out rcount 166 | rcount 167 | 168 | -------------------------------------------------------------------------------- /Chapter 3 Functions.R: -------------------------------------------------------------------------------- 1 | ###Chapter 3 Functions 2 | 3 | ###Function Documentation 4 | # Consult the documentation on the mean() function 5 | help(mean) 6 | 7 | # Inspect the arguments of the mean() function 8 | args(mean) 9 | 10 | ###Use A Function 11 | # The linkedin and facebook vectors have already been created for you 12 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 13 | facebook <- c(17, 7, 5, 16, 8, 13, 14) 14 | 15 | # Calculate average number of views 16 | avg_li = mean(linkedin) 17 | avg_fb = mean(facebook) 18 | 19 | # Inspect avg_li and avg_fb 20 | avg_li 21 | avg_fb 22 | 23 | # Calculate the mean of linkedin minus facebook 24 | mean(linkedin - facebook) 25 | 26 | ###Use A Function (2) 27 | # The linkedin and facebook vectors have already been created for you 28 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 29 | facebook <- c(17, 7, 5, 16, 8, 13, 14) 30 | 31 | # Calculate the mean of the sum 32 | avg_sum = mean(linkedin + facebook) 33 | 34 | # Calculate the trimmed mean of the sum 35 | avg_sum_trimmed = mean(linkedin + facebook, trim = 0.2) 36 | 37 | # Inspect both new variables 38 | avg_sum 39 | avg_sum_trimmed 40 | 41 | ###Use A Function (3) 42 | # The linkedin and facebook vectors have already been created for you 43 | linkedin <- c(16, 9, 13, 5, NA, 17, 14) 44 | facebook <- c(17, NA, 5, 16, 8, 13, 14) 45 | 46 | # Basic average of linkedin 47 | mean(linkedin) 48 | 49 | # Advanced average of linkedin 50 | mean(linkedin, na.rm = TRUE) 51 | 52 | ###Functions Inside Functions 53 | # The linkedin and facebook vectors have already been created for you 54 | linkedin <- c(16, 9, 13, 5, NA, 17, 14) 55 | facebook <- c(17, NA, 5, 16, 8, 13, 14) 56 | 57 | # Calculate the mean absolute deviation 58 | mean(abs(linkedin - facebook), na.rm = TRUE) 59 | 60 | ###Write Your Own Function 61 | # Create a function pow_two() 62 | pow_two <- function(x) { 63 | x ^ 2 64 | } 65 | 66 | # Use the function 67 | pow_two(12) 68 | 69 | # Create a function sum_abs() 70 | sum_abs <- function(x, y) { 71 | abs(x) + abs(y) 72 | } 73 | 74 | # Use the function 75 | sum_abs(-2, 3) 76 | 77 | ###Write Your Own Function (2) 78 | # Define the function hello() 79 | hello <- function() { 80 | print("Hi there!") 81 | TRUE 82 | } 83 | 84 | # Call the function hello() 85 | hello() 86 | 87 | # Define the function my_filter() 88 | my_filter <- function(x) { 89 | if (x > 0) { 90 | return(x) 91 | } else { 92 | return(NULL) 93 | } 94 | } 95 | 96 | # Call the function my_filter() twice 97 | my_filter(5) 98 | my_filter(-5) 99 | 100 | ###Write Your Own Function (3) 101 | # Extend the pow_two() function 102 | pow_two <- function(x, print_info = TRUE) { 103 | y <- x ^ 2 104 | if (print_info) { 105 | print(paste(x, "to the power two equals", y)) 106 | } 107 | return(y) 108 | } 109 | 110 | ###Function Scoping 111 | two_dice <- function() { 112 | possibilities <- 1:6 113 | dice1 <- sample(possibilities, size = 1) 114 | dice2 <- sample(possibilities, size = 1) 115 | dice1 + dice2 116 | } 117 | 118 | ###R Passes Arguments By Value 119 | increment <- function(x, inc = 1) { 120 | x <- x + inc 121 | x 122 | } 123 | count <- 5 124 | a <- increment(count, 2) 125 | b <- increment(count) 126 | count <- increment(count, 2) 127 | 128 | ###R You Functional? 129 | # The linkedin and facebook vectors have already been created for you 130 | 131 | # Define the interpret function 132 | interpret <- function(num_views) { 133 | if (num_views > 15) { 134 | print("You're popular!") 135 | return(num_views) 136 | } else { 137 | print("Try to be more visible!") 138 | return(0) 139 | } 140 | } 141 | 142 | # Call the interpret function twice 143 | interpret(linkedin[1]) 144 | interpret(facebook[2]) 145 | 146 | ###R You Functional? (2) 147 | # The linkedin and facebook vectors have already been created for you 148 | linkedin <- c(16, 9, 13, 5, 2, 17, 14) 149 | facebook <- c(17, 7, 5, 16, 8, 13, 14) 150 | 151 | # The interpret() can be used inside interpret_all() 152 | interpret <- function(num_views) { 153 | if (num_views > 15) { 154 | print("You're popular!") 155 | return(num_views) 156 | } else { 157 | print("Try to be more visible!") 158 | return(0) 159 | } 160 | } 161 | 162 | # Define the interpret_all() function 163 | interpret_all <- function(views, return_sum = TRUE) { 164 | count <- 0 165 | for (v in views) { 166 | count <- count + interpret(v) 167 | } 168 | if (return_sum) { 169 | return(count) 170 | } else { 171 | return(NULL) 172 | } 173 | } 174 | 175 | # Call the interpret_all() function on both linkedin and facebook 176 | interpret_all(linkedin) 177 | interpret_all(facebook) 178 | 179 | ###Load An R Package 180 | # The mtcars vectors have already been prepared for you 181 | wt <- mtcars$wt 182 | hp <- mtcars$hp 183 | 184 | # Request the currently attached packages 185 | search() 186 | 187 | # Try the qplot() function with wt and hp 188 | qplot(wt, hp) 189 | 190 | # Load the ggplot2 package 191 | library("ggplot2") 192 | 193 | # Retry the qplot() function 194 | qplot(wt, hp) 195 | 196 | # Check out the currently attached packages again 197 | search() 198 | 199 | -------------------------------------------------------------------------------- /Chapter 4 The Apply Family.R: -------------------------------------------------------------------------------- 1 | ###Chapter 4 The Apply Family 2 | 3 | ###Use lapply With A Built-In R Function 4 | # The vector pioneers has already been created for you 5 | pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857") 6 | 7 | # Split names from birth year: split_math 8 | split_math <- strsplit(pioneers, split = ":") 9 | 10 | # Convert to lowercase strings: split_low 11 | split_low <- lapply(split_math, tolower) 12 | 13 | # Take a look at the structure of split_low 14 | str(split_low) 15 | 16 | ###Use lapply With Your Own Function 17 | # Code from previous exercise: 18 | pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857") 19 | split <- strsplit(pioneers, split = ":") 20 | split_low <- lapply(split, tolower) 21 | 22 | # Write function select_first() 23 | select_first <- function(x) { 24 | x[1] 25 | } 26 | 27 | # Apply select_first() over split_low: names 28 | names <- lapply(split_low, select_first) 29 | 30 | # Write function select_second() 31 | select_second <- function(x) { 32 | x[2] 33 | } 34 | 35 | ###lapply And Anonymous Functions 36 | # Definition of split_low 37 | pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857") 38 | split <- strsplit(pioneers, split = ":") 39 | split_low <- lapply(split, tolower) 40 | 41 | names <- lapply(split_low, function(x) { x[1] }) 42 | 43 | years <- lapply(split_low, function(x) { x[2] }) 44 | 45 | ###Use lapply With Additional Arguments 46 | # Definition of split_low 47 | pioneers <- c("GAUSS:1777", "BAYES:1702", "PASCAL:1623", "PEARSON:1857") 48 | split <- strsplit(pioneers, split = ":") 49 | split_low <- lapply(split, tolower) 50 | 51 | # Replace the select_*() functions by a single function: select_el 52 | select_el <- function(x, index) { 53 | x[index] 54 | } 55 | 56 | # Call the select_el() function twice on split_low: names and years 57 | names <- lapply(split_low, select_el, index = 1) 58 | years <- lapply(split_low, select_el, index = 2) 59 | 60 | ###Apply Functions That Return NULL 61 | lapply(split_low, function(x) { 62 | if (nchar(x[1]) > 5) { 63 | return(NULL) 64 | } else { 65 | return(x[2]) 66 | } 67 | }) 68 | 69 | ###How To Use sapply 70 | # temp has already been defined in Data Camp's workspace 71 | 72 | # Use lapply() to find each day's minimum temperature 73 | lapply(temp, min) 74 | 75 | # Use sapply() to find each day's minimum temperature 76 | sapply(temp, min) 77 | 78 | # Use lapply() to find each day's maximum temperature 79 | lapply(temp, max) 80 | 81 | # Use sapply() to find each day's maximum temperature 82 | sapply(temp, max) 83 | 84 | ###sapply With Your Own Function 85 | # temp is already defined in the workspace 86 | 87 | # Define a function calculates the average of the min and max of a vector: extremes_avg 88 | extremes_avg <- function(x) { 89 | (min(x) + max(x))/2 90 | } 91 | 92 | # Apply extremes_avg() over temp using sapply() 93 | sapply(temp, extremes_avg) 94 | 95 | # Apply extremes_avg() over temp using lapply() 96 | lapply(temp, extremes_avg) 97 | 98 | ###sapply With Function Returning Vector 99 | # temp is already available in the workspace 100 | 101 | # Create a function that returns min and max of a vector: extremes 102 | extremes <- function(x) { 103 | c(min = min(x), max = max(x)) 104 | } 105 | 106 | # Apply extremes() over temp with sapply() 107 | sapply(temp, extremes) 108 | 109 | # Apply extremes() over temp with lapply() 110 | lapply(temp, extremes) 111 | 112 | ###sapply Can't Simplify, Now What? 113 | # temp is already prepared for you in the workspace 114 | 115 | # Create a function that returns all values below zero: below_zero 116 | below_zero <- function(x) { 117 | return(x[x < 0]) 118 | } 119 | 120 | # Apply below_zero over temp using sapply(): freezing_s 121 | freezing_s <- sapply(temp, below_zero) 122 | 123 | # Apply below_zero over temp using lapply(): freezing_l 124 | freezing_l <- lapply(temp, below_zero) 125 | 126 | # Compare freezing_s to freezing_l using identical() 127 | identical(freezing_s, freezing_l) 128 | 129 | ###sapply With Functions That Return NULL 130 | # temp is already available in the workspace 131 | 132 | # Write a function that 'cat()s' out the average temperatures: print_info 133 | print_info <- function(x) { 134 | cat("The average temperature is", mean(x), "\n") 135 | } 136 | 137 | # Apply print_info() over temp using lapply() 138 | sapply(temp, print_info) 139 | 140 | # Apply print_info() over temp using sapply() 141 | lapply(temp, print_info) 142 | 143 | ###Reverse Engineering sapply 144 | sapply(list(runif (10), runif (10)), 145 | function(x) c(min = min(x), mean = mean(x), max = max(x))) 146 | 147 | ###Use vapply 148 | # temp is already available in the workspace 149 | 150 | # Code the basics() function 151 | basics <- function(x) { 152 | c(min = min(x), mean = mean(x), max = max(x)) 153 | } 154 | 155 | # Apply basics() over temp using vapply() 156 | vapply(temp, basics, numeric(3)) 157 | 158 | ###Use vapply (2) 159 | # temp is already available in the workspace 160 | 161 | # Definition of the basics() function 162 | basics <- function(x) { 163 | c(min = min(x), mean = mean(x), median = median(x), max = max(x)) 164 | } 165 | 166 | # Fix the error: 167 | vapply(temp, basics, numeric(4)) 168 | 169 | ###From sapply To vapply 170 | # temp is already defined in the workspace 171 | 172 | # Convert to vapply() expression 173 | vapply(temp, max, numeric(1)) 174 | 175 | # Convert to vapply() expression 176 | vapply(temp, function(x, y) { mean(x) > y }, logical(1), y = 5) 177 | 178 | # Definition of get_info (don't change) 179 | get_info <- function(x, y) { 180 | if (mean(x) > y) { 181 | return("Not too cold!") 182 | } else { 183 | return("Pretty cold!") 184 | } 185 | } 186 | 187 | # Convert to vapply() expression 188 | vapply(temp, get_info, character(1), y = 5) 189 | 190 | -------------------------------------------------------------------------------- /Chapter 5 Utilities.R: -------------------------------------------------------------------------------- 1 | ###Chapter 5 Utilities 2 | 3 | ###Mathematical Utilities 4 | # The errors vector has already been defined for you 5 | errors <- c(1.9,-2.6,4.0,-9.5,-3.4,7.3) 6 | 7 | # Sum of absolute rounded values of errors 8 | sum(round(abs(errors))) 9 | 10 | ###Find The Error 11 | # Don't edit these two lines 12 | vec1 <- c(1.5,2.5,8.4,3.7,6.3) 13 | vec2 <- rev(vec1) 14 | 15 | # Fix the error 16 | mean(c(abs(vec1), abs(vec2))) 17 | 18 | ###Data Utilities 19 | # The linkedin and facebook vectors have already been created for you 20 | linkedin <- list(16, 9, 13, 5, 2, 17, 14) 21 | facebook <- list(17, 7, 5, 16, 8, 13, 14) 22 | 23 | # Convert linkedin and facebook to a vector: li_vec and fb_vec 24 | li_vec <- unlist(linkedin) 25 | fb_vec <- unlist(facebook) 26 | 27 | # Append fb_vec to li_vec: social_vec 28 | social_vec <- append(li_vec, fb_vec) 29 | 30 | # Sort social_vec 31 | sort(social_vec, decreasing = TRUE) 32 | 33 | ###Find The Error (2) 34 | # Fix me 35 | round(sum(unlist(list(1.1,3,5)))) 36 | 37 | # Fix me 38 | rep(seq(1, 7, by = 2), times = 7) 39 | 40 | ###Beat Gauss Using R 41 | # Create first sequence: seq1 42 | seq1 <- seq(1, 500, by = 3) 43 | 44 | # Create second sequence: seq2 45 | seq2 <- seq(1200, 900, by = -7) 46 | 47 | # Calculate total sum of the sequences 48 | sum(seq1) + sum(seq2) 49 | 50 | ###grepl & grep 51 | # The emails vector has already been defined for you 52 | emails <- c("john.doe@ivyleague.edu", "education@world.gov", "dalai.lama@peace.org", 53 | "invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv") 54 | 55 | # Use grepl() to match for "edu" 56 | grepl("edu", emails) 57 | 58 | # Use grep() to match for "edu", save result to hits 59 | hits <- grep("edu", emails) 60 | 61 | # Subset emails using hits 62 | emails[hits] 63 | 64 | ###grepl & grep (2) 65 | # The emails vector has already been defined for you 66 | emails <- c("john.doe@ivyleague.edu", "education@world.gov", "dalai.lama@peace.org", 67 | "invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv") 68 | 69 | # Use grepl() to match for .edu addresses more robustly 70 | grepl("@.*\\.edu$", emails) 71 | 72 | # Use grep() to match for .edu addresses more robustly, save result to hits 73 | hits <- grep("@.*\\.edu$", emails) 74 | 75 | # Subset emails using hits 76 | emails[hits] 77 | 78 | ###sub & gsub 79 | # The emails vector has already been defined for you 80 | emails <- c("john.doe@ivyleague.edu", "education@world.gov", "global@peace.org", 81 | "invalid.edu", "quant@bigdatacollege.edu", "cookie.monster@sesame.tv") 82 | 83 | # Use sub() to convert the email domains to datacamp.edu 84 | sub("@.*\\.edu$", "@datacamp.edu", emails) 85 | 86 | ###sub & gsub (2) 87 | awards <- c("Won 1 Oscar.", 88 | "Won 1 Oscar. Another 9 wins & 24 nominations.", 89 | "1 win and 2 nominations.", 90 | "2 wins & 3 nominations.", 91 | "Nominated for 2 Golden Globes. 1 more win & 2 nominations.", 92 | "4 wins & 1 nomination.") 93 | 94 | sub(".*\\s([0-9]+)\\snomination.*$", "\\1", awards) 95 | 96 | ###Right Here, Right Now 97 | # Get the current date: today 98 | today <- Sys.Date() 99 | 100 | # See what today looks like under the hood 101 | unclass(today) 102 | 103 | # Get the current time: now 104 | now <- Sys.time() 105 | 106 | # See what now looks like under the hood 107 | unclass(now) 108 | 109 | ###Create And Format Dates 110 | # Definition of character strings representing dates 111 | str1 <- "May 23, '96" 112 | str2 <- "2012-03-15" 113 | str3 <- "30/January/2006" 114 | 115 | # Convert the strings to dates: date1, date2, date3 116 | date1 <- as.Date(str1, format = "%b %d, '%y") 117 | date2 <- as.Date(str2) 118 | date3 <- as.Date(str3, format = "%d/%B/%Y") 119 | 120 | # Convert dates to formatted strings 121 | format(date1, "%A") 122 | format(date2, "%d") 123 | format(date3, "%b %Y") 124 | 125 | ###Create And Format Times 126 | # Definition of character strings representing times 127 | str1 <- "May 23, '96 hours:23 minutes:01 seconds:45" 128 | str2 <- "2012-3-12 14:23:08" 129 | 130 | # Convert the strings to POSIXct objects: time1, time2 131 | time1 <- as.POSIXct(str1, format = "%B %d, '%y hours:%H minutes:%M seconds:%S") 132 | time2 <- as.POSIXct(str2) 133 | 134 | # Convert times to formatted strings 135 | format(time1, "%M") 136 | format(time2, "%I:%M %p") 137 | 138 | ###Calculations With Dates 139 | # day1, day2, day3, day4 and day5 are available in Data Camp's workspace 140 | 141 | # Difference between last and first pizza day 142 | day5 - day1 143 | 144 | # Create vector pizza 145 | pizza <- c(day1, day2, day3, day4, day5) 146 | 147 | # Create differences between consecutive pizza days: day_diff 148 | day_diff <- diff(pizza) 149 | 150 | # Average period between two consecutive pizza days 151 | mean(day_diff) 152 | 153 | ###Calculations With Times 154 | # login and logout are already defined in the workspace 155 | # Calculate the difference between login and logout: time_online 156 | time_online <- logout - login 157 | 158 | # Inspect the variable time_online 159 | time_online 160 | 161 | # Calculate the total time online 162 | sum(time_online) 163 | 164 | # Calculate the average time online 165 | mean(time_online) 166 | 167 | ###Time Is Of The Essence 168 | # Convert astro to vector of Date objects: astro_dates 169 | # Source: www.timeanddate.com 170 | astro_dates <- as.Date(astro, format = "%d-%b-%Y") 171 | 172 | # Convert meteo to vector of Date objects: meteo_dates 173 | meteo_dates <- as.Date(meteo, format = "%B %d, %y") 174 | 175 | # Calculate the maximum absolute difference between astro_dates and meteo_dates 176 | max(abs(meteo_dates - astro_dates)) 177 | 178 | --------------------------------------------------------------------------------