Special functions: Syntactic sugar
Everything is a function!
- Backticks:
Useful for those column name: percent (%) smthing
- $ Accessing element in name
## [1] "b"
## [1] "a"
# better use [[]], see also exact = FALSe if needed
# can also be use names that are generated programmatically
what <- "spam"
x[[what]]
## [1] "a"
Curly braces
{
works like function call
evaluate everything -> return last result
is also a function
Operator are functions!
## [1] TRUE
- defining your own binary operators (or more)
## [1] 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5
## [1] 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5
9.0.12 Replacement functions!
x <- 1:5 # example input
x[3] <- 0 # replace the third element with 0
length(x) <- 7 # "replace" length
names(x) <- LETTERS[seq_along(x)]
x
## A B C D E F G
## 1 2 0 4 5 NA NA
Example in the spatial world: sf::st_crs()
`add<-` <- function(x, where=TRUE, value) # the where = true is nice!
{
x[where] <- x[where] + value
x # the modified object that will replace the original one
}
y <- 1:5
add(y) <- 10 # calls y <- `add<-`(y, value=10)
print(y)
## [1] 11 12 13 14 15
y
must exist before the call
9.0.12.2 replacing attributes
names<-
, class<-
, dim<-
, levels<-
, colnames<-
: you can use use attr<-
and attributes<-
x <- "spam"
attributes(x) <- list(shape="oval", smell="meaty")
attributes(x) <- c(attributes(x), taste="umami")
attr(x, "colour") <- "rose"
print(x)
## [1] "spam"
## attr(,"shape")
## [1] "oval"
## attr(,"smell")
## [1] "meaty"
## attr(,"taste")
## [1] "umami"
## attr(,"colour")
## [1] "rose"
Setting an attribute to NULL remove it.