Special functions: Syntactic sugar

Everything is a function!

  • Backticks:

Useful for those column name: percent (%) smthing

  • $ Accessing element in name
x <- list(spam="a", eggs="b", `eggs and spam`="c", best.spam.ever="d")
x$eggs
## [1] "b"
x$s # dangerous partial matching
## [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!

x <- list(1:5, 11:17, 21:23)
all.equal(Map(`[`, x, 1),  Map(function(e) e[1], x)) 
## [1] TRUE
# I admit I prefer the second one
  • defining your own binary operators (or more)
`(^.^)` <- function(e1, e2) (e1+e2)/2
`(^.^)`(5, 1:10)
##  [1] 3.0 3.5 4.0 4.5 5.0 5.5 6.0 6.5 7.0 7.5
#unsure what is specila about %%
`%:)%` <- function(e1, e2) (e1+e2)/2
5 %:)% 1:10
##  [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

add(bill) <- 10
#Error in add(bill) <- 10 : object 'bill' not found

9.0.12.1 exercice 9.18

`extend<-` <- function(x, value) {
  c(x, value)  
}
x <- 1
extend(x) <- 2  
extend(x) <- 3:10 
x
##  [1]  1  2  3  4  5  6  7  8  9 10

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.