Bastien - 1 year ago 91

R Question

I have what appears to be a simple problem but I can't figure out a way to fix it simply. I need to find a way to transform a numerical vector a way that it is increasing. A example will be clearer...

`vec1 <- c(3,3,2,3,1)`

After passe into a function

f(vec1)

should become

`# [1] 1 1 2 1 3`

The same way,

`vec2 <- c(1,3,1,2,7)`

should become

`# [1] 1 2 1 3 4`

and

`vec3 <- c(2,1,0,0,4)`

should become

`# [1] 1 2 3 3 4`

Initially I've though that

`as.numeric(as.factor(vec1))`

would have worked but it's not working anymore (new version?)

For people that wonder why I need that, it's related to a bug in the raster package which I've presented here:

http://r-sig-geo.2731867.n2.nabble.com/bug-in-raster-stackApply-when-raster-not-in-memory-td7590584.html

but got no answer. I then have to find a workaround.

I hope it's clear,

Thanks

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

We can create a function with `match`

```
f1 <- function(x){
match(x, unique(x))
}
f1(vec1)
#[1] 1 1 2 1 3
f1(vec2)
#[1] 1 2 1 3 4
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**