set.seed(1234)
df <- tibble::tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
(df$a - min(df$a, na.rm = TRUE)) /
(max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
## [1] 0.3319492 0.7647291 1.0000000 0.0000000 0.8089534 0.8313814 0.5162933
## [8] 0.5244878 0.5192926 0.4243735
(df$b - min(df$b, na.rm = TRUE)) /
(max(df$b, na.rm = TRUE) - min(df$b, na.rm = TRUE))
## [1] 0.15265375 0.00000000 0.06506096 0.31129943 0.57344857 0.26011813
## [7] 0.14274906 0.02553760 0.04721860 1.00000000
(df$c - min(df$c, na.rm = TRUE)) /
(max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
## [1] 0.7821670 0.4733256 0.4981101 0.9430704 0.3729606 0.0000000 1.0000000
## [8] 0.2098653 0.7084006 0.2532211
(df$d - min(df$d, na.rm = TRUE)) /
(max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))
## [1] 1.0000000 0.5192783 0.4480343 0.5114592 0.1678518 0.3084450 0.0000000
## [8] 0.2556247 0.5745131 0.5222322
rescale <- function(x) {
x <- (x-min(x, na.rm = TRUE)) /
(max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
return(x)
}
df$a <- rescale(df$a)
df$b <- rescale(df$b)
df$c <- rescale(df$c)
df$d <- rescale(df$d)
Conditional Execution
detect_sign <- function(x) {
if(x > 0) {
message("Value is Positive)")
print(x)
} else if (x==0) {
warning("Value is not positive, but it can be accepted")
print(x)
} else {
stop("Value is negative, the function must stop")
print(x)
}
}
3 %>% detect_sign()
## Value is Positive)
## [1] 3
0 %>% detect_sign()
## Warning in detect_sign(.): Value is not positive, but it can be accepted
## [1] 0
Function Arguments
?mean
## starting httpd help server ... done
x <- c(1:10,100,NA)
x
## [1] 1 2 3 4 5 6 7 8 9 10 100 NA
x %>% mean()
## [1] NA
x %>% mean(na.rm = TRUE)
## [1] 14.09091
x %>% mean(na.rm = TRUE, trim = 0.1)
## [1] 6
mean_remove_na <- function(x, na.rm = TRUE, ...) {
avg <- mean(x, na.rm = na.rm, ...)
return(avg)
}
x %>% mean_remove_na()
## [1] 14.09091
x %>% mean_remove_na(na.rm = FALSE)
## [1] NA
x %>% mean_remove_na(trim = 0.1)
## [1] 6