Creating a factor from a numeric variable

后端 未结 2 1865
我在风中等你
我在风中等你 2021-01-29 00:27

I am quite new to R and I am having some troubles with creating factors. I should create a factor from a numeric variable. This factor should have three levels: dissatisfied (v

相关标签:
2条回答
  • 2021-01-29 00:45

    I would probably just use cut:

    > x <- 0:10
    > cut(x = x,breaks = c(0,4,5,10),include.lowest = TRUE,
          labels = c('Dissatisfied','Either/Or','Satisfied'))
     [1] Dissatisfied Dissatisfied Dissatisfied Dissatisfied Dissatisfied Either/Or    Satisfied    Satisfied   
     [9] Satisfied    Satisfied    Satisfied   
    Levels: Dissatisfied Either/Or Satisfied
    
    0 讨论(0)
  • 2021-01-29 00:51

    To collapse groups, you can use the list syntax for levels<-. For example

    # test data
    soep <- data.frame(lsat = letters[1:10])
    
    lsat_factor <- factor(soep$lsat)
    
    table(lsat_factor)
    # lsat_factor
    # a b c d e f g h i j 
    # 1 1 1 1 1 1 1 1 1 1 
    
    levels(lsat_factor) <- list(
        "Dissatisfied"=levels(lsat_factor)[1:4],
        "Neither/nor" = levels(lsat_factor)[5],
        "Satisfied" = levels(lsat_factor)[6:10]
    )
    
    table(lsat_factor)
    # lsat_factor
    # Dissatisfied  Neither/nor    Satisfied 
    #            4            1            5 
    
    0 讨论(0)
提交回复
热议问题