Useful R snippets
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 <- 1 value2 <- 0
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 <- paste("values=c(",name1,"=",value1,",", name2,"=",value2,")",sep="") values <- eval(parse(text=command))
After issuing those command a vector named values is going to be created with named entries and values as follows
Steve Bill 1 0
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
Filed under: R / R-Code | 5 Comments