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

后端 未结 3 1112
栀梦
栀梦 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: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/

提交回复
热议问题