R Warning: Mistake in factor

后端 未结 2 574
傲寒
傲寒 2021-01-06 22:56

My R code is:

means_log_adj <- aggregate(lab_data[,delta_touse], 
    by = list(
        factor(mydata_adj$Response_EP, labels = c(\"non_responder\", \"re         


        
2条回答
  •  梦谈多话
    2021-01-06 23:20

    After some trial and error I managed to reproduce your problem.

    But let me start by saying that there is a very important difference between a warning and an error in R. When you report a problem, be sure to distinguish clearly between the two.

    x <- letters[1:5]
    factor(x, labels=LETTERS[1:10])
    
    Error in factor(x, labels = LETTERS[1:10]) : 
      invalid labels; length 10 should be 1 or 5
    

    This error occurs because you are telling factor() to re-label the data with levels that don't exist. I have specified 10 labels for a variable that only contains 5 levels. This means the labels and levels don't match.

    There are two ways to fix this:

    The first is to let R determine the levels, and simply call factor(x) without any parameters. (At a guess, this is probably what you should have done in your code.):

    factor(x)
    [1] a b c d e
    Levels: a b c d e
    

    The second is to call factor(x) and specifying the levels, not the labels:

    factor(x, levels=letters[1:10])
    [1] a b c d e
    Levels: a b c d e f g h i j
    

    You haven't provided sample data, so we can't test a solution. But try the following code:

    means_log_adj <- aggregate(lab_data[,delta_touse], 
        by = list(
            factor(mydata_adj$Response_EP,), 
            factor(mydata_adj$sex), 
            factor(mydata_adj$timepoint)),
        mean)
    

提交回复
热议问题