Avoid rbind()/cbind() conversion from numeric to factor

后端 未结 3 1109
栀梦
栀梦 2021-01-30 21:20

I\'m trying to build a dataset before plotting it. I decided to use function factory gammaplot.ff() and the first version of my code looks like this:



        
相关标签:
3条回答
  • 2021-01-30 21:27

    If I use rbind or rbind.data.frame, the columns are turned into characters every time. Even if I use stringsAsFactors = FALSE. What worked for me was using

    rbind.data.frame(df, data.frame(ColNam = data, Col2 = data), stringsAsFactors = FALSE)
    
    0 讨论(0)
  • 2021-01-30 21:47

    You can use rbind.data.frame and cbind.data.frame instead of rbind and cbind.

    0 讨论(0)
  • 2021-01-30 21:48

    I want to put @mtelesha 's comment to the front.

    Use stringsAsFactors = FALSE in cbind or cbind.data.frame:

    x <- data.frame(a = letters[1:5], b = 1:5)
    y <- cbind(x, c = LETTERS[1:5])
    class(y$c)
    ## "factor"
    y <- cbind.data.frame(x, c = LETTERS[1:5])
    class(y$c)
    ## "factor"
    y <- cbind(x, c = LETTERS[1:5], stringsAsFactors = FALSE)
    class(y$c)
    ## "character"
    y <- cbind.data.frame(x, c = LETTERS[1:5], stringsAsFactors = FALSE)
    class(y$c)
    ## "character"
    

    UPDATE (May 5, 2020):

    As of R version 4.0.0, R uses a stringsAsFactors = FALSE default in calls to data.frame() and read.table().

    https://developer.r-project.org/Blog/public/2020/02/16/stringsasfactors/

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