Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch convert columns to numeric type

Tags:

r

I have a dataframe with a bunch of columns that I need to convert to the numeric type. I have written the following code to try to do this, however it is saying the replacement has 0 rows.

instanceconvert <- colnames(regmodel[7:262])  for (i in instanceconvert) {   regmodel$i <- as.numeric(regmodel$i) } 

Any help would be appreciated.

like image 238
Scohen Avatar asked Oct 02 '13 20:10

Scohen


People also ask

How do you make multiple columns as numeric?

Use the lapply() Function to Convert Multiple Columns From Integer to Numeric Type in R. Base R's lapply() function allows us to apply a function to elements of a list. We will apply the as. numeric() function.

How do I convert a column to numeric?

To convert a column to numeric in R, use the as. numeric() function. The as. numeric() is a built-in R function that returns a numeric value or converts any value to a numeric value.

How do I convert columns to numeric in pandas?

The best way to convert one or more columns of a DataFrame to numeric values is to use pandas. to_numeric() . This function will try to change non-numeric objects (such as strings) into integers or floating-point numbers as appropriate.

How do I convert multiple columns to int in Python?

1. astype() to Convert multiple float columns to int Pandas Dataframe. The astype() method allows us to pass datatype explicitly, even we can use Python dictionary to change multiple datatypes at a time, where keys specify the column and values specify the new datatype.


2 Answers

You can use sapply for this:

dat <- sapply( dat, as.numeric ) 

If not every column needs converting:

library( taRifx ) dat <- japply( dat, which(sapply(dat, class)=="character"), as.numeric ) 
like image 118
Ari B. Friedman Avatar answered Oct 09 '22 00:10

Ari B. Friedman


Here is quick solution from other question:

df[] <- lapply(df, function(x) as.numeric(as.character(x)))

Reference: Change all columns from factor to numeric in R

like image 45
Andrii Avatar answered Oct 09 '22 00:10

Andrii