【发布时间】:2021-06-16 22:19:30
【问题描述】:
我想将一些列从“chr”或“num”更改为“factor”,其余列不受影响,这是我的代码:
>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)])
所以上面的代码可以解决我的问题,但是太麻烦了,我知道“:=”操作符可以就地更新data.table的列,请问这里如何使用“:=”来更新NO.1列,2,4,6 和 7?或其他方便或简单的方法?
【问题讨论】:
-
参见
?:=中的示例,从“## using lapply & .SD”开始。
标签: r data.table