Skip to navigation

R: loops vs apply (vectorization)

February 10th, 2010

A helpful article in by Uwe Ligges and John Fox in R news 2008(1), pp 46-50, about loops vs. apply was just pointed out on R-help. I’ve uploaded it here (pdf).

My first RMySQL session

January 21st, 2010
# 'fai1' is an empty MySQL database for which 'mpromber' has all privileges
mycon <- dbConnect(MySQL(),user='mpromber',dbname='fai1') # pass seems to be read from ~/.my.cnf
# dsub is a data frame:
dbWriteTable(mycon,"dsub",dsub) # create table "dsub"
dbDisconnect(mycon) # close connection

Time for lunch.

MySQL settings in ~/.my.cnf

January 21st, 2010

You can specify default settings for MySQL in the file ~/.my.cnf (create it if it doesn’t exist). E.g., you could spare yourself typing your password each time you connect with an entry in that file like this:

[client]
password='mypassword'

This gets loaded in addition to the system configuration file, which for me is at /etc/mysql/my.cnf.

r-cran-rmysql

January 20th, 2010

Memo to self: I installed RMySQL using

sudo aptitude install r-cran-rmysql

because when I used

install.packages("RMySQL")

it asked my to specify the MySQL libraries and headers and whatnot and don’t know where they are.

Use R to help with lottery drawing

January 7th, 2010

When you start using R, it can be confusing that if you assign something to an object you do not get visual feedback:

x <- rep(1:3,5)

You have to then type x to see it:

> x
 [1] 1 2 3 1 2 3 1 2 3 1 2 3 1 2 3

You can exploit this fact for doing a quick-and-dirty lottery. Assume you have a file with email addresses, one per line, called "entries.txt". First, read them and assign them to an object:

entries <- readLines("entries.txt")

Next, create an index of numbers of the same length but in random order:

index <- sample(1:length(entries),length(entries))

Note that you don't see it unless you type index. Combine index and emails in a dataframe (also not directly visible):

dat <- data.frame(cbind(index,entries))

Now, go to random.org and draw a number from the index. Type dat to reveal who you drew. This method makes it a bit more "blind" and a bit less likely that you'll cheat.