R COMMANDS AND TRICKS R commands, shortcuts, and tricks I find to be elegant or tend to forget. 1. replace values in a vector x <- c("a", "b", "a", "o", "b") y <- c(a = "apple", b = "bannana", o = "orange")[x] > y # a b a o b # "apple" "bannana" "apple" "orange" "bannana" 2. replace values in a vector (reversed dictionary) x <- c("a", "b", "a", "o", "b") d <- c(apple = "a", bannana = "b", orange = "o") y <- names(d)[match(x, d)] > y # [1] "apple" "bannana" "apple" "orange" "bannana" 3. replace intervals with group names x <- c(2, 16, 88, 15, 33, 1, 21) d <- c(baby = 0, toddler = 2, child = 6, teen = 12, adult = 18, senior = 65) y <- names(d)[findInterval(x, d)] > y # [1] "toddler" "teen" "senior" "teen" "adult" "baby" "adult" 4. repeat string values multiple times x <- c("-", "o", "-") y <- strrep(x, c(4, 2, 4)) > y # [1] "----" "oo" "----" 5. generate equally distributed factor levels y <- gl(2, 4, labels = c("male", "female")) > y # [1] male male male male female female female female # Levels: male female 6. get interactions between two factors and their levels x <- factor(c("M", "F")) y <- factor(c("young", "old")) > x:y # [1] M:young F:old # Levels: F:old F:young M:old M:young 7. subtract means from each column of a matrix x <- data.matrix(iris) x <- x - colMeans(x)[col(x)] x <- x / apply(x, 2, sd)[col(x)] 8. order/sort each row of a matrix x <- data.matrix(iris) x <- matrix(col(x)[order(row(x), x)], nrow=nrow(x), byrow=TRUE) x <- matrix(x[order(row(x), x)], nrow=nrow(x), byrow=TRUE)