[英]Specifying level for each value of a column in a data frame
My question is simple but somehow I can`t figure it out. 我的问题很简单,但是以某种方式我无法弄清楚。
I have an increasing numeric vector in which values are not unique. 我有一个越来越多的数值向量,其中值不是唯一的。
a <- c(1,2,4,4,7,7,7,9,12,25,25,26)
I want to create another column b which will give me the corresponding level of each of the element of vector a. 我想创建另一个列b,它将为我提供向量a的每个元素的相应级别。 Here, b is: 在这里,b是:
b <- c(1,2,3,3,4,4,4,5,6,7,7,8)
Can someone please help me how do I achieve it? 有人可以帮我实现它吗?
This should do it: 应该这样做:
as.integer(factor(a))
Or this is probably better: 或者这可能更好:
match(a, unique(a))
use cumsum
and diff
,hope it help,thanks. 使用cumsum
和diff
,希望对您有所帮助,谢谢。
b=cumsum(c(TRUE,diff(a)!=0))
b
[1] 1 2 3 3 4 4 4 5 6 7 7 8
Also, 也,
findInterval(a, unique(a))
#[1] 1 2 3 3 4 4 4 5 6 7 7 8
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.