(photo credit) In this post we collect several R one- or few-liners that we consider useful. As our minds tend to forget these little fragments we jot them down here so we will find them again.
Indexing in nested loops
Every once in a while I run a nested loop like the following one.
for (i in 1:3) for (j in 1:4) print(paste(i, j))
Now if I want to save all the subsequent values in a vector I might do it like this.
res for (i in 1:3) for (j in 1:4) res[(i-1)*4 + j]
This is pretty tedious especially when more than two loops are nested. A simple though less efficient alternative is to use the append function.
res for (i in 1:3) for (j in 1:4) res
Subsequently re-calling a function that takes two arguments
Suppose we wanted to call a function that takes two arguments and use the results as a argument to the same function again. For example may want to sum up the values 1 to 5 Of course the function sum will do this for us, but what if this function didn’t exist? We might of course write:
1 + 2 + 3 + 4 + 5
But how do that in a single function call? Using do.call or the like will not work, as the function "+" takes two arguments.
The trick is to use the function Reduce.
Reduce("+", 1:5) > 15
Evaluating an R command stored in a character string
From time to time, you may encounter situations where you have to evaluate a command which is stored in a character string. For example, let’s assume that we have the following variables:
name1 <- "Steve" name2 <- "Bill" value1 value2
Now, what would you do if you have to create a vector with entries whose value is stored in the variables value1 and value2 and entry names whose value is stored in the variables name1 and name2? You can write:
command command eval(parse(text=command))
Creating an empty dataframe with zero rows
Sometimes I want to fill up a dataframe from the frist row on. It might be useful do start off with a dataframe with zero rows for that purpose. The function numeric or character do the job. In case we wanted to specify a factor with predefined levels also factor may be useful.
data.frame(a=numeric(), b=numeric()) data.frame(a=numeric(), b=character(), c=factor(levels=1:10), stringsAsFactors=F)
… to be continued.
Tamas and Mark