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.
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.
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.
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.
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.
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 )
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With