2017-06-16 70 views
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] 
+1

您可以使用'grep(patt,x,value = TRUE)'而不是'x [grep(patt,x)]'。我认为你的问题是由于没有必要时选择评分而导致的。 '(score):='应该工作......在右边,如果你有多个列,使用'mget'。有关转换为数字的信息,请参阅https://stackoverflow.com/q/16846380/。 – Frank

回答

1

感谢@Frank的建议。

tbl[,(score):=lapply(.SD, as.numeric),.SDcols=score] 
相关问题