Numbering elements in a vector

后端 未结 3 1347
误落风尘
误落风尘 2021-01-20 06:16

I would like to number the elements of a vector, assigning \'1\' to the smallest element in the vector. I know how to do this, but my solution (code included below) seems o

相关标签:
3条回答
  • 2021-01-20 06:37

    If you're using numeric or integer data you can use as.numeric(factor())

    dat <- c(5,8,12,12,8,3,100)
    as.numeric(factor(dat))
    

    Also, as a side note, you should avoid using data as a variable name in R since its already a built-in function.

    0 讨论(0)
  • 2021-01-20 06:44

    Another possibility is:

    > rank(data)
    [1] 2.0 3.5 5.5 5.5 3.5 1.0 7.0
    

    You can see the argument "ties.method" for how to handle ties.

    0 讨论(0)
  • 2021-01-20 06:58

    More compact version of your program.

    dat <- c(5,8,12,12,8,3,100)
    dat_sorted <- sort(unique(dat))
    match(dat,dat_sorted)
    
    0 讨论(0)
提交回复
热议问题