10 R One Liners to Impress Your Friends

June 5, 2011
By

(This article was first published on DataDebrief, and kindly contributed to R-bloggers)

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

#lists
lapply(list(1:4),function(n){n*2})
# otherwise
(1:4)*2

Sum a List of Numbers

#lists
lapply(list(1:4),sum)

# otherwise
sum(unlist(list(1:4))) # or simply
sum(1:4)

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('http://search.twitter.com/search.atom?&q=R-Project', 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

# http://cran.r-project.org/web/packages/doSMP/vignettes/gettingstartedSMP.pdf
# 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)

To leave a comment for the author, please follow the link and comment on their blog: DataDebrief.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Sponsors

Mango solutions



plotly webpage

dominolab webpage



Zero Inflated Models and Generalized Linear Mixed Models with R

Quantide: statistical consulting and training

datasociety

http://www.eoda.de





ODSC

ODSC

CRC R books series





Six Sigma Online Training









Contact us if you wish to help support R-bloggers, and place your banner here.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)