[R] Question on substitute.

From: Simon Knapp <sleepingwell_at_gmail.com>
Date: Wed, 12 Mar 2008 00:12:07 +1100


I have a data frame of around 4500 rows which contain file name prefixes and other interesting variables. each prefix corresponds to multiple files and a I only have 4300 complete sets of files. If any one of the files is missing for a given prefix, then the function I use fails. The effect is emulated by the function "f" and data "dummy.data":

f <- function(x) if(runif(1) < 0.1) stop('oops') else rnorm(10) dummy.data <- data.frame(cbind(paste('a', 1:100, sep=''), matrix(rnorm(9000),nrow=100, ncol=9)))

I would like the results as a data.frame and if it weren't for the errors would do:

res <- apply(dummy.data, 1, function(x) try(f(x))) #... though I wouldn't really need the try would I.
#dimnames(res)[[2]] <- as.character(dummy.data[,1])

but the errors make res a list and the second line fails. I can do:

res <- NULL
for(i in 1:nrow(dummy.data)) if(class(tmp <- try(f(dummy.data[i,])))
!= 'try-error') res <- cbind(res, tmp)

which gives me the correct result, but I don't know which column of res belongs to which row of dummy.data.

I can get the desired result with with:

#--- desired result --------
res <- NULL
for(i in 1:nrow(dummy.data)) if(class(tmp <- try(f(dummy.data[i,])))
!= 'try-error')

    eval(parse(text=paste("res <- cbind(res,", dummy.data[i,1], "=tmp)", sep='')))

#------------------------------

but it is sort of ugly and I was hoping I could do something like:

res <- NULL
for(i in 1:nrow(dummy.data)) if(class(tmp <- try(f(dummy.data[i,])))
!= 'try-error')

    res <- eval(substitute(cbind(res, a=b), list(a=dummy.data[i,1], b=tmp)))

but the a is not being substituted (not that this is prettier, but I'm trying to come to grips with
substitute/do.call/calls/expressions/...). I guess that argument names are a different beast to argument values in expressions.

My question (finally) is: is there a way of achieving 'desired result', but using 'quote', 'substitute' or any other similar functions/idioms I've not run into yet? Alternatively, is there a completely different way?

Any help appreciated,
Simon Knapp.



R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Tue 11 Mar 2008 - 13:15:13 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 11 Mar 2008 - 14:30:20 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive