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

后端 未结 5 1422
無奈伤痛
無奈伤痛 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:22

    For multiple columns and a function applied on column values.

    When updating the values from a function, the RHS must be a list object, so using a loop on .SD with lapply will do the trick.

    The example below converts integer columns to numeric columns

    a1 <- data.table(a=1:5, b=6:10, c1=letters[1:5])
    sapply(a1, class)  # show classes of columns
    #         a           b          c1 
    # "integer"   "integer" "character" 
    
    # column name character vector
    nm <- c("a", "b")
    
    # Convert columns a and b to numeric type
    a1[, j = (nm) := lapply(.SD, as.numeric ), .SDcols = nm ]
    
    sapply(a1, class)
    #         a           b          c1 
    # "numeric"   "numeric" "character" 
    

提交回复
热议问题