Monday, June 6, 2011

10 R One Liners to Impress Your Friends

Following the trend of one liners for various languages (Haskell, Scala, Python), here's some examples in R

Multiply Each Item in a List by 2
# otherwise

Sum a List of Numbers

# otherwise
sum(unlist(list(1:4))) # or simply
Verify if Exists in a String
wordlist = c("lambda", "data", "plot", "statistics", "R")
tweet = c("R is an integrated suite of software facilities for data manipulation, calculation and graphical display")
wordlist[wordlist %in% (c(unlist(strsplit(tweet,' ', fixed=T))))]

Read in a File
readLines("data.file", n=-1)

Happy Birthday to You!
lapply((1:4),function(x){ paste(c("Happy Birthday to ", ifelse(x!=3, "you", "dear Name")), sep="", collapse="")})

Filter list of numbers
n = c(49, 58, 76, 82, 88, 90); c(list(n[which(n<=60)]),list(n[which(n>60)]))
Fetch and Parse an XML web service
library('XML'); xmlParseDoc('', asText=F)

Find minimum (or maximum) in a List
# for lists
lapply(list(c(14, 35, -7, 46, 98)), min, classes="numeric", how="replace")

# otherwise
min(unlist(list(14, 35, -7, 46, 98)))
# or simply
min(c(14, 35, -7, 46, 98))
max(c(14, 35, -7, 46, 98))

Parallel Processing
# copy from Section 4 An example doSMP session
library(doSMP); w <- startWorkers(workerCount = 4); registerDoSMP(w); foreach(i = 1:3) %dopar% sqrt(i)

Sieve of Eratosthenes
##ok, this one is a little cheating
library('spuRs'); primesieve(c(),2:50)


  1. For summing a list of numbers, take a look at what happens if you have more than one element in your list. Compare these two calls:

    lapply(list(1, 2, 3, 4), sum), list(1, 2, 3, 4))

    For detecting substrings, you might want to take a look at str_detect in the stringr package.

    In your filtering example, you don't need the calls to which.

    Otherwise, great job. did you see the realted question on stackoverflow?

  2. Excellent, thank you muchly Richie for the suggestions, and pointing out the terrible oversight with the sum example.

    Did not know about str_detect, that stringr package looks like something I can use!

    Some great one liners in that stackoverflow link, thanks for pointing me that way too.

    - Mark