# Load packages
# Core
library(tidyverse)
library(tidyquant)
# For reproducible work
set.seed(1234)
# Create a data frame
df <- tibble::tibble(
a = rnorm(10),
b = rnorm(10),
c = rnorm(10),
d = rnorm(10)
)
# Re-scale each column
df$a <- (df$a - min(df$a, na.rm = TRUE)) /
(max(df$a, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$b <- (df$b - min(df$b, na.rm = TRUE)) /
(max(df$b, na.rm = TRUE) - min(df$a, na.rm = TRUE))
df$c <- (df$c - min(df$c, na.rm = TRUE)) /
(max(df$c, na.rm = TRUE) - min(df$c, na.rm = TRUE))
df$d <- (df$d - min(df$d, na.rm = TRUE)) /
(max(df$d, na.rm = TRUE) - min(df$d, na.rm = TRUE))
rescale <- function(x) {
# body
x <- (x - min(x, na.rm = TRUE)) /
(max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
# return value
return(x)
}
df$a <- rescale(df$a)
df$a <- rescale(df$b)
df$a <- rescale(df$c)
df$a <- rescale(df$d)
df
## # A tibble: 10 × 4
## a b c d
## <dbl> <dbl> <dbl> <dbl>
## 1 1 0.216 0.782 1
## 2 0.519 0 0.473 0.519
## 3 0.448 0.0919 0.498 0.448
## 4 0.511 0.440 0.943 0.511
## 5 0.168 0.810 0.373 0.168
## 6 0.308 0.368 0 0.308
## 7 0 0.202 1 0
## 8 0.256 0.0361 0.210 0.256
## 9 0.575 0.0667 0.708 0.575
## 10 0.522 1.41 0.253 0.522
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 negetive, the function must stop")
print(x)
}
}
3 %>% detect_sign()
## [1] 3
0 %>% detect_sign()
## [1] 0
1 -1 %>% detect_sign()
## [1] 1
## [1] 0
?mean
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
two types of functions