Sunday, 25 June 2006

One more juicy R tip

If you're like me, you get tired of writing:

mydata[complex.row.condition, complex.column.condition] <- mydata[complex.row.condition, complex.column.condition]+1

or similar. One solution is:

crc <- complex.row.condition
ccc <- complex.column.condition
mydata[crc,ccc]<-mydata[crc,ccc]+1
rm(ccc,crc)

which saves writing out the complex conditions more than once. But it also makes it very cluttered to read and unclear what you are doing.

My alternative solution is to place this function definition in your Rprofile.site file:

inplace <- function (f, arg=1) eval.parent(call("<-",substitute(f)[[arg+1]], f),2)

Now instead of writing, e.g.

foo[bar,baz] <- foo[bar,baz]*2

you can just write

inplace(foo[bar,baz] *2)

or instead of

foo[bar,baz] <- paste(foo[bar,baz], 1:10)

do

inplace(paste(foo[bar,baz], 1:10))

The second argument of the inplace function allows you to use it when your target for assignment is not the first argument of your inner function. For example:

inplace(sub("old", "new", foo[bar,baz]), 3)

is the same as

foo[bar,baz] <- sub("old", "new", foo[bar,baz])