Batch convert columns to numeric type

前端 未结 6 2144
眼角桃花
眼角桃花 2021-01-01 11:20

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 replacem

6条回答
  •  不思量自难忘°
    2021-01-01 11:36

    As SenorO pointed out, the reason your original code does not work is that $i will not evaluate i to find out it's current value. You should instead access and assign to the column using double brackets, which work when i is a name or index number:

    for (i in instanceconvert)
    {
      regmodel[[i]] <- as.numeric(regmodel[[i]])
    }
    

    Following Ari's approach, you can get rid of the loop:

    regmodel[,instanceconvert] <- 
        lapply(regmodel[,instanceconvert,drop=FALSE],as.numeric)
    

    You could also do this with your range, 7:262, in place of "instanceconvert", since you can access/assign by name or column number.

提交回复
热议问题