Batch convert columns to numeric type

前端 未结 6 2011
眼角桃花
眼角桃花 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.

    0 讨论(0)
  • 2021-01-01 11:40

    Just pass the columns you want as a data frame d into the following:

    data.frame(apply(d, 2, as.numeric))
    

    This goes column by column and converts each into a numeric. Then just change your row-names and column-names accordingly.

    0 讨论(0)
  • 2021-01-01 11:42

    You can use sapply for this:

    dat <- sapply( dat, as.numeric )
    

    If not every column needs converting:

    library( taRifx )
    dat <- japply( dat, which(sapply(dat, class)=="character"), as.numeric )
    
    0 讨论(0)
  • 2021-01-01 11:53

    A fast a dirty way to do it, especially if you have variables all over that need converting, which would mean a lot of conversion code is to write the file out and read it back in again using something like write.csv/read.csv

    write.csv(regmodel, file="regmodel.csv")
    read.csv(file="regmodel.csv")
    
    0 讨论(0)
  • 2021-01-01 11:57

    Here is quick solution from other question:

    df[] <- lapply(df, function(x) as.numeric(as.character(x)))

    Reference: Change all columns from factor to numeric in R

    0 讨论(0)
  • 2021-01-01 11:57

    Combining the answer by @Andrii with the comment by @RobertYi, my short suggestion is

    df[] <- sapply(df, as.numeric)
    

    This ensures that the result stays as data frame.

    0 讨论(0)
提交回复
热议问题