Is there a generic way to refer to the last column of an R data frame in a formula object?
r
Solution
Here is a simple solution, using dummy data
DF <- data.frame(matrix(runif(260), ncol = 26))
names(DF) <- paste0("V", seq_len(ncol(DF)))
Here I employ `tail()` to select the name of the last column in `DF` and build the formula from there.
f <- as.formula(paste(tail(names(DF), 1), "~ ."))
> f
V26 ~ .
Problem
I want to write a generic script to find the information gain of a set of features with respect to the final column. For instance, in a data frame built from a matrix with 26 columns, I'd write: ``` information.gain(V26~.,table) ``` The problem is that the formula V26~. doesn't have an obvious generic form. My first thought was to try this: ``` > nms <- colnames(table) > nms[length(nms)] [1] "V26" > information.gain(nms[length(nms)]~., table) Error in model.frame.default(formula, data, na.action = NULL) : variable lengths differ (found for 'V1') ``` which seemed wrong on account of nms being a vector of strings. Is there a way to coerce the name into something that can be part of a formula?