Change all columns from factor to numeric in R

后端 未结 4 1533
走了就别回头了
走了就别回头了 2020-12-10 22:20

I am working with a big dataset that is causing some trouble because some of the columns I the dataset are being treated as factors. How can I convert all of the columns fro

4条回答
  •  臣服心动
    2020-12-10 23:06

    This works but I'm thinking your data has an odd character or space, something that makes it read in as factor. You can try reading in with the argument stringsAsFactors = FALSE. But still wouldn't address character vs numeric read in. Here's a fix:

    data[] <- lapply(data, function(x) as.numeric(as.character(x)))
    
    ## > str(data)
    ## 'data.frame':   8 obs. of  4 variables:
    ##  $ v1: num  22.39 43.72 58.54 56.88 1.66 ...
    ##  $ v2: num  144.4 72.3 119.4 112.4 35.8 ...
    ##  $ v3: num  7 4 7 10 18 5 10 13
    ##  $ v4: num  5 0 3 4 18 3 4 7
    

提交回复
热议问题