0
votes

quick question. I have a table (Data) with a series of columns having similar colnames colnames(Data):

[Sum_Flag_x_30,Sum_Flag_y_60,...Sum_Flag_z_n].

I ideally want to write a simple code to get all of these into numeric format (as.numeric). Tried with:

Data[,grep("Sum_Flag",colnames(Data),value=T)] <- as.numeric(Data[,grep("Sum_Flag",colnames(Data),value=T)]

but it's not working and I get the following error:

Error in [<-.data.table(*tmp*, , grep("Sum_Flag", colnames(Data), : Supplied 25 items to be assigned to 55057 items of column 'Sum_Flag_x_30'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.

Any clue about this?

Thanks guys Ciao

1
Your question is unclear.. Do you want to rename the colnames and then change that to numeric? As in, "Sum_Flag_x_30" would become "30"? - eduardokapp
Hi,sorry. I don't want to rename the columns, just want to trasform the class of the data in these columns into numeric (as.numeric(Data$var)), since they are originally imported as chr. - Roberto92

1 Answers

0
votes

All you have to do is use apply. Apply as.numeric() to every column, by doing:

# margin = 2 means that you're applying a function column-wise.
new_data <- apply(Data, MARGIN = 2, as.numeric)