[R] Ensure parameter is a string when passed within an lapply & called function runs a 'substitute' on it

Andrew Clancy nite at achren.org
Mon May 9 23:39:27 CEST 2016


I’m trying to solve what looks like the same issue as stack overflow article, but within an lapply:

I’ve replicated the issue with partialPlot below in ‘testFunc’. The lines up to the final print can’t change (including the substitute). In the first call it prints out ‘X1’ correctly, in the second it prints out ‘var’. I’ve tried eval, quote etc as the article suggests. Any ideas?

numObs  <- 10
numVars <- 6
dataSet    <- data.frame(replicate(numVars,rnorm(numObs)))
# partialPlot(x = model, pred.data = dataSet, x.var = 'X1', plot = F) 

testFunc <- function(x, pred.data, x.var, plot=F) {
  x.var <- substitute(x.var)
  # print(paste('is.character(x.var)', is.character(x.var), 'is.name(x.var)', is.name(x.var)))
  xname <- if (is.character(x.var)) x.var else {
    if (is.name(x.var)) deparse(x.var) else {
  # print(head(pred.data[,xname]))

vars <- names(dataSet)[[1]]
testFunc(x = model, pred.data = dataSet, x.var = local(vars), plot = F)

lapply(vars, function(var) {
  # print(paste('var', var))
  testFunc(x = model, pred.data = dataSet, x.var = var, plot = F)

	[[alternative HTML version deleted]]

More information about the R-help mailing list