R QUIRKS Weird and unexpected corners of R. 1. matrix element names vec <- setNames(1:9, letters[1:9]) # vector with names() mat <- matrix(vec, 3, 3) # names() are not preserved names(mat) <- letters[1:9] # now mat elements has names() mat["b"] # works mat <- mat[,] # names are lost after any subsetting mat["b"] # error 2. assignment syntax for turning elements into NA vec <- 1:9 is.na(vec) <- c(3,5) # turns 3rd and 5th elements into NA 3. factor level interactions with ":" f1 <- factor(c("young", "old", "young")) f2 <- factor(c("male", "female", "female")) f1:f2 # same as interaction(f1, f2) 4. selecting elements from a nested list without stacking brackets l <- list(1, 2, list(3, 4, list(5))) l[[c(3,3,1)]] # returns "5" 5. assignment to operators # function to tranform 'x' so that sum of 'x' and 'y' is equal to 'value' `+<-` <- function(x, y, value) value - y x <- 1 y <- 4 x + y # 5 x + y <- 10 # transform x so that x + y = 10 x + y # 10 x # 6 y # 4 # can also be used with built-int and custom %% operators `%in%<-` <- function(x, y, value) {x[x %in% y] <- value; x} vec <- letters[1:4] vec %in% c("a", "c") # TRUE, FALSE, TRUE, FALSE vec %in% c("a", "c") <- "o" # turns 1st and 3rd elements of vec to "o"