I want to changes some columns from "chr" or "num" to "factor", and the remaining columns are not affected, Here is my code:
>library("data.table")
>titanic <- fread("titanic.csv")
>str(titanic)
Classes ‘data.table’ and 'data.frame': 887 obs. of 8 variables:
$ Survived : int 0 1 1 1 0 0 0 0 1 1 ...
$ Pclass : int 3 1 3 1 3 3 1 3 3 2 ...
$ Name : chr "Mr. Owen Harris Braund" "Mrs. John Bradley (Florence Briggs Thayer) Cumings" "Miss. Laina Heikkinen" "Mrs. Jacques Heath (Lily May Peel) Futrelle" ...
$ Sex : chr "male" "female" "female" "female" ...
$ Age : num 22 38 26 35 35 27 54 2 27 14 ...
$ Siblings/Spouses Aboard: int 1 1 0 1 0 0 0 3 0 1 ...
$ Parents/Children Aboard: int 0 0 0 0 0 0 0 1 2 0 ...
$ Fare : num 7.25 71.28 7.92 53.1 8.05 ...
>titanic_tmp <- titanic[, lapply(.SD,function(x) factor(x,levels = unique(x))),.SDcols =c(1,2,4,6,7)]
>titanic <- cbind(titanic_tmp,titanic[,c(3,5,8)])
So the code above can solve my problem, but it's too cumbersome,I know that ":=" operator could update data.table columns in-place, How can I use ":=" here to update column NO.1,2,4,6 and 7? or other convenient or simple way to do this?