0
我有一個data.table
列表,我想將一些列轉換爲數字並執行rowSums
。我想弄清楚如何將所有列轉換爲數字。如何使用data.table列表中的函數分配多個列?
這是我試過的。
# Obtain data
tbl<-get_data(sqlquery = tqry, dbase=db1, server=serv)
# Names of the columns that need to be converted to numeric
score<-names(tbl)[grep('score',names(tbl),ignore.case = T)]
tbl[,class(AcceptingNewPatientsScore)]
[1] "character"
### Wrong - Having problem here
tbl[,eval(score):=as.numeric(get(score))]
tbl[,class(AcceptingNewPatientsScore)]
[1] "numeric" # It converted but jumbled scores.
tbl[,tscore:=rowSums(.SD,na.rm = FALSE),.SDcols=score]
您可以使用'grep(patt,x,value = TRUE)'而不是'x [grep(patt,x)]'。我認爲你的問題是由於沒有必要時選擇評分而導致的。 '(score):='應該工作......在右邊,如果你有多個列,使用'mget'。有關轉換爲數字的信息,請參閱https://stackoverflow.com/q/16846380/。 – Frank