Code Quality
Blank Lines
Generally, your code quality needs some improvement. For example, insert blank lines. So instead of
factors <- rownames(attr(tf, "factors"))
tvars <- attr(tf, "variables")
tlabs <- attr(tf, "term.labels")
I would suggest
factors <- rownames(attr(tf, "factors"))
tvars <- attr(tf, "variables")
tlabs <- attr(tf, "term.labels")
Order Within A Script or Source Code
Generally, one puts package import statements at the top of a file. Which you are not doing, and you also give no reason why you are doing it. So I would put library(lazyeval)
at the top.
Further, you set variables before you use them. For example, factors <- rownames(attr(tf, "factors"))
.
These observations lead to the following script.
# to use 'as.lazy' and 'lazy_eval'
library(lazyeval)
dat <- data.frame(
A = c("a", "b", "c"),
B = c("x", "y", "z"),
NotUsed = c(1, 2, 3))
frml <- ~ A + B + A:B
tf <- terms.formula(frml)
tvars <- attr(tf, "variables")
used <- lapply(eval(tvars, envir = dat), as.factor)
names(used) <- rownames(attr(tf, "factors"))
tlabs <- attr(tf, "term.labels")
lapply(tlabs, function(tlab){
droplevels(lazy_eval(as.lazy(tlab), data = used))
})
Please pay attention to how a grouped the code lines.
A Better Way
Regarding a better way, for which you have asked, I would propose the following.
dat <- data.frame(A = c("a", "b", "c"),
B = c("x", "y", "z"),
NotUsed = c(1, 2, 3))
dat <- subset(x = dat, select = -NotUsed)
dat$c <- as.factor(paste(dat$A, dat$B, sep = ":"))
my.list <- lapply(dat,
FUN = function(column)
{
return(column)
})
In my view, this is a better way because it expresses your intention better. If you would have given me your code without any comments I would have a hard time explaining what it does or what it's purpose is. In addition, it does not require an additional package.
HTH!