Vaibhav - 1 year ago 39

R Question

I have a dataframe with 2 columns, Item and Rank

`a <- data.frame(item=c('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'),rank=1:26)`

I want to change the rank of the item 't' whose current rank is 20 to rank 10 and shift the item whose current rank is 10 i.e 'j' by one rank down and so it gets the new rank 11 and so on with for the rest of the data frame with 's' getting the new rank 20

The data frame would look something like this

`b <- data.frame(item=c('a','b','c','d','e','f','g','h','i','t','j','k','l','m','n','o','p','q','r','s','u','v','w','x','y','z'),rank=1:26)`

Answer Source

If you know which ranks you will change you can use a function like this, while `x`

is the data.frame, `y`

the rank of the value you want to change and `z`

the target rank.

```
foo <- function(x, y, z){
x$rank[c(z, y)] <- c(z+0.1, z) # specify the new ranks
x <- x[order(x$rank),] # order
x$rank <- 1:nrow(x) # update the rank
x}
foo(a, 20, 10)
item rank
1 a 1
2 b 2
3 c 3
4 d 4
5 e 5
6 f 6
7 g 7
8 h 8
9 i 9
20 t 10
10 j 11
11 k 12
12 l 13
13 m 14
14 n 15
15 o 16
16 p 17
17 q 18
18 r 19
19 s 20
21 u 21
22 v 22
23 w 23
24 x 24
25 y 25
26 z 26
```