Reputation: 1778
I have a data.table
list and I want to convert some of the columns to numeric and perform rowSums
. I am trying to figure out how to convert all the columns to numeric.
This is what I have tried.
# 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]
Upvotes: 0
Views: 287
Reputation: 1778
Thanks to @Frank for his suggestion.
tbl[,(score):=lapply(.SD, as.numeric),.SDcols=score]
Upvotes: 1