Search code examples
rdcast

Get factor variable name without using apostrophs


How could I refer to a variable new in a function without writing them as string or indexing before. I want to construct a function where I can replace grouping variables easily.

For example:

final_table %>% data.table::dcast(Lipids ~ combi_new)

Another time this factor variable could be named differently. e.g., group_2 It doesn't work with final_table[,2] - how could I solve this?

Thanks, Nadine


Solution

  • I'm not sure I understand the question, are you trying to build the formula for a dcast from the column indices?
    Maybe that answers your problem:

    library(data.table)
    setDT(final_table)
    colnames(final_table)
    measurevar <- colnames(final_table)[2]
    groupvar <- colnames(final_table)[1]
    valvar <- colnames(final_table)[3]
    formula <- as.formula(paste(measurevar, groupvar, sep=" ~ "))
    test <- dcast(final_table, formula, value.var = valvar)