0

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]
JeanVuda
  • 1,738
  • 14
  • 29
  • 1
    Instead of `x[grep(patt, x)]`, you can use `grep(patt, x, value=TRUE)`. I think your problem is caused by choosing to eval score when there is no need. `(score) :=` should work... On the right hand side, if you have multiple columns, use `mget`. See https://stackoverflow.com/q/16846380/ maybe regarding conversion to numeric. – Frank Jun 16 '17 at 22:25

1 Answers1

1

Thanks to @Frank for his suggestion.

tbl[,(score):=lapply(.SD, as.numeric),.SDcols=score]
JeanVuda
  • 1,738
  • 14
  • 29