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
?
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.
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.
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.
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)).
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)
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