Reclassify select columns in Data Table

后端 未结 3 1916
忘掉有多难
忘掉有多难 2021-02-06 10:40

I wish to change the class of selected variables in a data table, using a vectorized operation. I am new to the data.table syntax, and am trying to learn as much as possible. I

相关标签:
3条回答
  • 2021-02-06 10:50

    You could avoid the overhead of the construction of .SD within j by using set

    for(j in index) set(data, j =j ,value = as.character(data[[j]]))
    
    0 讨论(0)
  • 2021-02-06 10:59

    You just need to use .SDcols with your index vector (I learnt that today!), but that will just return a data table with the reclassed columns. @dickoa 's answer is what you are looking for.

    data <- data[, lapply(.SD, as.character) , .SDcols = index ]
    sapply(data , class)
            id      height      weight 
    "character" "character" "character" 
    
    0 讨论(0)
  • 2021-02-06 11:02

    I think that @SimonO101 did most of the Job

    data[, names(data)[index] := lapply(.SD, as.character) , .SDcols = index ]
    

    You can just use the := magic

    0 讨论(0)
提交回复
热议问题