Select / assign to data.table when variable names are stored in a character vector

后端 未结 5 1375
無奈伤痛
無奈伤痛 2020-11-22 03:54

How do you refer to variables in a data.table if the variable names are stored in a character vector? For instance, this works for a data.frame:

5条回答
  •  醉话见心
    2020-11-22 04:41

    *This is not an answer really, but I don't have enough street cred to post comments :/

    Anyway, for anyone who might be looking to actually create a new column in a data table with a name stored in a variable, I've got the following to work. I have no clue as to it's performance. Any suggestions for improvement? Is it safe to assume a nameless new column will always be given the name V1?

    colname <- as.name("users")
    # Google Analytics query is run with chosen metric and resulting data is assigned to DT
    DT2 <- DT[, sum(eval(colname, .SD)), by = country]
    setnames(DT2, "V1", as.character(colname))
    

    Notice I can reference it just fine in the sum() but can't seem to get it to assign in the same step. BTW, the reason I need to do this is colname will be based on user input in a Shiny app.

提交回复
热议问题