Recode/relevel data.frame factors with different levels

后端 未结 4 1130
予麋鹿
予麋鹿 2020-12-25 08:44

Each time when I have to recode some set of variables, I have SPSS recode function in mind. I must admit that it\'s quite straightforward. There\'s a similar recode

相关标签:
4条回答
  • 2020-12-25 08:51

    In this case, since you have numbers, why not just transform the numbers using modular arithmetic?

    eg

    levels(x) <- as.character((6*as.numeric(levels(x)))%%7+1)
    

    Modify the 6 and 7 as appropriate if using larger ranges.

    0 讨论(0)
  • 2020-12-25 08:55

    You must provide levels argument to factor (as Dirk wrote):

    set.seed(2342472)
    ( x <- round(runif(10,1,7)) )
    #  [1] 7 5 5 3 1 2 5 3 3 2
    ( xf <- as.factor(x) )
    # [1] 7 5 5 3 1 2 5 3 3 2
    # Levels: 1 2 3 5 7
    ( yf <- factor(x,levels=7:1) )
    # [1] 7 5 5 3 1 2 5 3 3 2
    # Levels: 7 6 5 4 3 2 1
    

    you could do this on existing factor too

    ( yxf <- factor(xf,levels=7:1) )
    # [1] 7 5 5 3 1 2 5 3 3 2
    #Levels: 7 6 5 4 3 2 1
    

    As you see levels were extended in desire order.

    0 讨论(0)
  • 2020-12-25 09:04

    Yes, just assign to levels:

    R> set.seed(100)
    R> x <- as.factor(round(runif(100,1,7)))
    R> table(x)
    x
     1  2  3  4  5  6  7 
     3 16 20 19 18 17  7 
    R> levels(x) <- LETTERS[1:7]
    R> table(x)
    x
     A  B  C  D  E  F  G 
     3 16 20 19 18 17  7 
    R> 
    
    0 讨论(0)
  • 2020-12-25 09:05

    If you complete the factor levels you're good to go:

    df <- data.frame(x=factor(c(2,4,5,6)))
    df$x <- factor(df$x, levels = 7:1)
    table(df$x)
    
    7 6 5 4 3 2 1 
    0 1 1 1 0 1 0 
    
    0 讨论(0)
提交回复
热议问题