17

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?

ZygD
  • 22,092
  • 39
  • 79
  • 102
Enric Agud Pique
  • 1,087
  • 7
  • 13
  • 30

1 Answers1

34

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)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • You are missing a comma, the code should read: ´dades[,2:13]´ otherwise you will introduce NAs by coercion on column 1 row 2:13. – krenz May 06 '22 at 12:23
  • 2
    @krenz Not really. By default `data.frame` with no comma in indexing, it is taken as column index. (But you are right that it is row,column index. ) You may be using a different data structure ie. data.table etc. – akrun May 06 '22 at 13:57
  • You are indeed correct. – krenz May 07 '22 at 14:13