I have a data frame, and make selections based on some of the factors. I want a vector of names, created from the factor levels. Hopefully this suffices to show the intent:
test.results <- list(
First = factor(c('A', 'B'), levels=c('A', 'B', 'C')),
Second = factor(c('E', 'F'), levels=c('E', 'F', 'G')),
Third = factor(c('X', 'Y'), levels=c('X', 'Y', 'Z'))
)
# cols <- c('First', 'Third'); TestName(test.results, cols) should return c('A X', 'B Y')
Here is an implementation. Is there a way to avoid the explicit ‘for’ loop?
TestName <- function(X, cols) {
result <- character(length(cols))
space <- '';
for (i in cols) {
result <- paste0(result, space, X[[i]]);
space <- ' ';
}
return(result);
}
Your data is not a data.frame in the example, but nevermind, the following will work regardless
pasteis vectorized, so as the question stands there should be no need for*applyorfor loopsYou could add checks about whether
xis alistand thatnamesexist inx.EDIT — allowing
septo be set (or other variables) if you wished.If your data was a
data.tablethen you could do the followingOr you could just stick with lists and data.frames and use
withorevalqor