Writing functions in R


This is the place to discuss questions in regards to designing your own functions in R.


Hello everyone…

Here is my problem:

I would like to use a function already established in a package, it looks like this:

nri(spectral data, value1, value2)

For value1 and value2 I would like to insert values, stored in a numeric vector, sequentially. Also, I would like to repeat this step until all possible combinations of the elements in my numeric vector have been used.


Can anybody help me here?




Hi Rene,

The code below should work… More elegant solutions are also possible using sapply()/lapply() instead of a for() loop, but the coding is perhaps less transparent.



my.vector <- 1:10 # vector of indices
my.combn <- combn(my.vector,2) # all possible combinations of 2 elements from my.vector
choose(length(my.vector),2) # number of unique combinations

my.results <- list() # container of results

for(i in 1:ncol(my.combn)) {
my.results[[i]] <- nri(spectral data,my.combn[1,i],my.combn[2,i])


That’s just great! Works fine. And I understand it:-) Thank you…


Does anyone see the error here? Loop works fine without trying to save plots in a list. When I want to store all 15 plots in a list, list objects are empty (NULL). The object subsets is a list containing 15 data.frames.

for (i in 1:length(subsets)){
plot_list = list()
labnames <- list(main=“Width”, xlab=“Wavelength [nm]”, ylab=“Reflectance [%]”)
set <- subsets[[i]]
set.2 <- as.matrix(set[,2:902])
f.res <- fdata(set.2, argvals = as.integer(names(set[,2:902])), names = labnames)
plot_list[[i]] <- plot(f.res, main = paste(as.vector(unique(data.wo.noise$Type))[i]))




Hi Rene,

The problem is that a call to the function plot() yields no output that is assignable to an object; It just prints to a graphic device:
dog <- plot(1) #yields a plot on screen but leaves dog as NULL
is.null(dog) # yields TRUE

You could instead save each plot command to a separate text string and then evaluate that command later using eval() and parse().

dog <- 'plot(1)'
eval(parse(text=dog)) #yields a plot on screen

Alternatively (my recommendation), you could just open a pdf() graphic device before running the loop, and then plot to that device within the loop. After you have finished the loop, use dev.off(). The pdf graphics device will add a new page for every plot, and keep all the pages in one document.