Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert several columns from integer to numeric in R data.frame

I would like to convert columns from 2 to 13 (the last one) from integer to numeric.

For one column, I use the following code:

dades$V3 <- as.numeric(dades$V3)

I want to convert columns from 2 to 13 with the same command. I create this vector:

dades<-2:13

Then, how do I use lapply?

like image 213
Enric Agud Pique Avatar asked Feb 10 '16 16:02

Enric Agud Pique


People also ask

How do I change the datatype of multiple columns in R?

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.

How do I convert specific columns to numeric in R?

To convert all the columns of the data frame to numeric in R, use the lapply() function to loop over the columns and convert to numeric by first converting it to character class as the columns were a factor.

How do I convert integer to numeric in R?

To convert factors to the numeric value in R, use the as. numeric() function. If the input is a vector, then use the factor() method to convert it into the factor and then use the as. numeric() method to convert the factor into numeric values.

How do I convert multiple columns into one in R?

To convert multiple columns into single column in an R data frame, we can use unlist function. For example, if we have data frame defined as df and contains four columns then the columns of df can be converted into a single by using data. frame(x=unlist(df)).


1 Answers

We can use lapply on the subset of dataset (dades[2:13]), convert to numeric and assign it back to those columns.

dades[2:13] <- lapply(dades[2:13], as.numeric)
like image 114
akrun Avatar answered Oct 12 '22 09:10

akrun