In R 4.2.0 it is now possible to pipe into a placeholder using the
|>
operator.
mean(state.area)
## [1] 72367.98
median(state.area)
## [1] 56222
smallest <- which.min(state.area)
c(state.area[smallest], state.name[smallest])
## [1] "1214" "Rhode Island"
largest <- which.max(state.area)
c(state.area[largest], state.name[largest])
## [1] "589757" "Alaska"
dot_product <- function(x, y) {
if (is.numeric(x) && is.numeric(y)) {
return(sum(x * y))
}
print("Both arguments must be numeric!")
}
dot_product(1:3, c(0, 1, 5))
## [1] 17
dot_product(2, 4)
## [1] 8
dot_product(c(1, 1), c("dog", "cat"))
## [1] "Both arguments must be numeric!"
frobenius_norm <- function(mx) {
if (!is.numeric(mx)) {
print("Argument must be numeric!")
} else if (!is.matrix(mx)) {
print("Argument must be a matrix!")
} else {
sqrt(sum(mx^2))
}
}
frobenius_norm(matrix(1:4, nrow = 2, ncol = 2))
## [1] 5.477226
frobenius_norm(c(3,5,7,10,15,21))
## [1] "Argument must be a matrix!"
frobenius_norm(matrix(c(3,5,7,10,15,21), nrow = 2, ncol = 3))
## [1] 29.1376
frobenius_norm(matrix(c(3,"fish",7,10,15,21), nrow = 2, ncol = 3))
## [1] "Argument must be numeric!"
compare_count <- function(x, y, comp = ">") {
if(!is.numeric(x) || !is.numeric(y)) {
print("Both vectors must be numeric!")
return()
}
if (length(x) != length(y)){
print("Both vectors must have the same length!")
return()
}
if (!(comp %in% c('>', '<', '='))) {
print("Unrecognized compare operator!")
return()
}
if (comp == '>') {
return(sum(x > y))
}
if (comp == '<') {
return(sum(x < y))
}
if (comp == '=') {
return(sum(x == y))
}
}
compare_count(rep(1, 5), rep(2, 5))
## [1] 0
compare_count(rep(1, 5), rep(2, 5), ">")
## [1] 0
compare_count(c(1, 2, 1, 2, 1), rep(2, 5), "<")
## [1] 3
compare_count(c(1, 2, 1, 2, 1), rep(2, 5), "=")
## [1] 2
compare_count(c(1, 2, 1, 2, 1), rep(2, 5), ">=")
## [1] "Unrecognized compare operator!"
## NULL
compare_count(c(1, 2, 1, 2, 1), rep(2, 6), "=")
## [1] "Both vectors must have the same length!"
## NULL
compare_count(c(1, 2, 1, 2, "owl"), rep(2, 6))
## [1] "Both vectors must be numeric!"
## NULL