Here’s a bunch of interesting R stuff I put together for learning and fun. Bookmark or re-download periodically as I may keep updating this page with more attractions.


See which packages and dataframes are currently attached

search()

Manually edit an R object, say, a function

fix(function) #edit in opened window and save

See, save and load command history

history(max.show=20)
history(Inf)
savehistory(file = "fname.txt")
loadhistory(file = "fname.txt")

Read a table with header

read.table("table.txt", header=T)
#or easier
read.delim("table.txt")

See first/last parts of an R object

head(table)
tail(table)

See manuals and references of R itself

help.start()

Check if an object exists

exists(x)

See all loaded packages with versions

sessionInfo()

Copy from clipboard

# Windows
a <- writeClipboard(as.character(factor.name))
a <- writeClipboard(as.character(numeric.variable))

# Mac
a <- read.table(pipe("pbpaste"), header = TRUE) 

Shut down computer after a wait time

library(fun)
shutdown(wait=10)  #10 sec

E-mail from within R

library(mailR)

send.mail(
    from="your@gmail.com", to="another@gmail.com", 
          subject="Hi there", body="How are you?", 
          smtp=list(host.name = "smtp.gmail.com", port = 25, 
          user.name = "yourusername", passwd = "yourpass", ssl = T), 
          authenticate = T, send=T, attach.files="link-to-file")

Create animated graphics in R

install.packages(“animation”)
saveGIF({
 # code for all plots
})

Various tolerance limits in R

.Machine

Make all possible concatenations out of two character vectors

a = c(200,400,600)
b = c(2,3,4)
comb = c( outer(a, b, FUN=paste, sep="-") )
comb
## [1] "200-2" "400-2" "600-2" "200-3" "400-3" "600-3" "200-4" "400-4" "600-4"

Make all possible concatenations out of multiple(>=2) character vectors

a = c("a","b")
b = c("A","B","C")
d = c("X","Y")
e = c("1","2","3")
out = as.character( Reduce( function(X,Y) outer(X,Y,FUN = paste, sep = "."), 
                     list(a, b, d, e) ) )
out
##  [1] "a.A.X.1" "b.A.X.1" "a.B.X.1" "b.B.X.1" "a.C.X.1" "b.C.X.1" "a.A.Y.1" "b.A.Y.1" "a.B.Y.1"
## [10] "b.B.Y.1" "a.C.Y.1" "b.C.Y.1" "a.A.X.2" "b.A.X.2" "a.B.X.2" "b.B.X.2" "a.C.X.2" "b.C.X.2"
## [19] "a.A.Y.2" "b.A.Y.2" "a.B.Y.2" "b.B.Y.2" "a.C.Y.2" "b.C.Y.2" "a.A.X.3" "b.A.X.3" "a.B.X.3"
## [28] "b.B.X.3" "a.C.X.3" "b.C.X.3" "a.A.Y.3" "b.A.Y.3" "a.B.Y.3" "b.B.Y.3" "a.C.Y.3" "b.C.Y.3"

List all functions used in an R script

library(NCmisc)
list.functions.in.file( filename = "blabla.R")

Print to a text file

# option 1
fileConn <- file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)

# option 2
sink("output.txt")
cat("hello")
cat("\n")
cat("world")
sink()

See size of an R object

x = rnorm(10000)
# Provides an estimate of the memory that is being used to store an R object
object.size(x)  # size in byte
## 80048 bytes
# But a better function for calculating exact size is
lobstr::obj_size(x)
## 80.05 kB
# They won't match for sequences because object.size does not correctly account
# for shared references and will return too large sizes. E.g., for sequences 
# created with :, R versions >= 3.5.0 only store the first and last numbers. 
object.size(1:2)
## 56 bytes
object.size(1:20000)
## 80048 bytes
lobstr::obj_size(1:2)
## 680 B
lobstr::obj_size(1:20000)
## 680 B

Get size of the workspace

workspace.size <- function() 
{
  ws <- sum(sapply(ls(envir=globalenv()), function(x)object.size(get(x))))
  class(ws) <- "object_size"
  ws
}
workspace.size()

See internal functions which are not loaded

getAnywhere(func)

See all names or all variables used in an expression

all.names(expression(sin(x+y)))
## [1] "sin" "+"   "x"   "y"
all.vars(expression(sin(x+y)))
## [1] "x" "y"

Change case of letters in a string

tolower("Hello")
## [1] "hello"
toupper("hello")
## [1] "HELLO"

Treat a vector as a one-column matrix to get dimensions

vec = 1:3
NCOL(vec)
## [1] 1
NROW(vec)
## [1] 3
nrow(NULL)
## NULL
NROW(NULL)  
## [1] 0

Make duplicates in a character vector unique

vec <- c("ab","cd","ef","ab")
make.unique(vec, sep = ".")  #appends sequence numbers to duplicates
## [1] "ab"   "cd"   "ef"   "ab.1"

Gather a bunch of objects in a list

#you can do
list(a=a, b=b, d=d, t=t)
#or, simply
mget(list(a,b,c,d))

Don’t print out numbers in scientific format, keep decimal form

options(scipen=999) 

Create an empty list of given length

a = vector("list", length = 3)
a
## [[1]]
## NULL
## 
## [[2]]
## NULL
## 
## [[3]]
## NULL

Show progress by increasing a counter (instead of printing i sequencially)

# check by running
for (i in 1:10) {
    cat(i, " \r")
    flush.console()
    Sys.sleep(0.3)
}

You cannot set the following names

_hi <- 2    #names cannot start with _
.hi <- 2    #names cannot start with .
?Reserved   #names cannot be a reserved word like if, else, etc.

Dataset related to U.S. states

state.abb
state.area
state.center
state.division
state.name
state.region
state.x77

How much memory is currently used by R?

lobstr::mem_used()

Define named vector in single line

x <- setNames(1:3, c("a", "b", "c"))

Avoiding else

if(x < 2) y=3 else y=NULL
# write simply as
y <- if(x < 2) 3

Avoiding multiple if-else

func <- function(x) {
  if (x == "a") {
    "option 1"
  } else if (x == "b") {
    "option 2" 
  } else if (x == "c") {
    "option 3"
  } else {
    stop("Invalid `x` value")
  }
}
# a more compact way to write the above
func <- function(x) {
  switch(x,
    a = "option 1",
    b = "option 2",
    c = "option 3",
    stop("Invalid `x` value")
  )
}

Evaluate a multivariate function over a grid of values

f = function(x,y,z) x + y + z
mapply(f, 1:3, 4:6, 7:9)
## [1] 12 15 18

Get list of all functions currently in global environment

funs <- Filter(is.function, mget(ls()))
names(fun)

Get list of all objects of an attached package

library(dplyr)
ls("package:dplyr")

Find the index of the first/last vector element satisfying a condition

Find( function(x){x^2 < 10}, 1:20, right=FALSE )
Find( function(x){x^2 < 10}, 1:20, right=TRUE )

Piping

f = function(x) x+2
g = function(y) 3*y
f(g(4))
## [1] 14
# another way using piping operator
library(magrittr)
4 %>% g() %>% f()
## [1] 14

Function arguments can be defined interdependently

f = function(x, y=2*x){x + y}
f(3)
## [1] 9

Function arguments can be defined in terms of body variables

f = function(x, y=a){
    a = 3
    x+y
}
f(10)

Set a variable in the global environment from within a function environment

f <- function(){
    zz <<- 5        # called super assignment
    zz+4
}
f()
## [1] 9
zz
## [1] 5

Intersect all possible combinations of list elements

l <- list(A=c("one", "two", "three", "four"), B=c("one", "two"), C=c("two", "four", "five", "six"), D=c("six", "seven"))
l
## $A
## [1] "one"   "two"   "three" "four" 
## 
## $B
## [1] "one" "two"
## 
## $C
## [1] "two"  "four" "five" "six" 
## 
## $D
## [1] "six"   "seven"
crossprod(table(stack(l)))
##    ind
## ind A B C D
##   A 4 2 2 0
##   B 2 2 1 0
##   C 2 1 4 1
##   D 0 0 1 2

Turn a matrix into a list of its columns

mat = diag(4)
as.list(as.data.frame(mat))

Combinations of n elements of a vector, taken m at a time

combn(vector,m)








\[\\[1in]\]

\[\\[3in]\]