0

I have a data frame with 25 variables.

I would like to convert the columns 2:8 ; 10:17 ; 24:25 as numeric.

I am using a separate for loops to convert the data type. Is there a way, i could use a single for loop and convert them to numeric.

Also, I wanted to convert 9, 18 in date format.

It would be helpful, if you could help me to minimise my code to single for loop

for (i in 2:8){
  claim[,i] <- as.numeric(claim[,i])
}

for(i in 10:17){
  claim[,i] <- as.numeric(claim[,i])
}

for(i in 24:25){
  claim[,i] <- as.numeric(claim[,i])
}
Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
Rohi
  • 385
  • 2
  • 3
  • 15

2 Answers2

0

This is not super efficient, but the first thing that comes to mind is defining a vector that contains the indices that you want to transform, and then iterating across it like this:

indices <- c(2:8, 10:17, 24:25)

for(i in indices) {
  claim[,i] <- as.numeric(claim[,i])
}
apax
  • 160
  • 7
0

Try this one row code:

claim[,c(2:8,10:17,24:25)] <- lapply(claim[,c(2:8,10:17,24:25)], as.numeric)

Adaptation of this answer.

The same could be done with date convertion:

claim[,c(9,18)] <- lapply(claim[,c(9,18)], as.Date)
Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39