Jeffkrop
Jeffkrop

Reputation: 389

Add 1 to value as rank increases

I am working with some grouped ranked data that has a latitude and longitude I would like to add 0.00075 to the latitude field every time the rank increases 1.

Below is one of the 5000 groups and it is unknown what the max rack will be so I need this to with within a group_by ideally using dplyr.

I know I can use a

group_by(loc_id) %>% mutate(y = if_else(rank > 1, as.character(Y + 0.00075), as.character(Y))

but this only works one time.

Here is some r code to build a dataframe full of data

id <- c(1,2,3,4,5)
loc_id <- c(77,77,77,77,77)
x <- c(-74.001981, -74.001981, -74.001981, -74.001981, -74.001981)
y <- c(40.736038, 40.736038, 40.736038, 40.736038, 40.736038)
views <- c(55,45,66,22,99)
rank <- c(3,4,2,5,1)
data <- data.frame(id, loc_id, x, y, views, rank)

Upvotes: 2

Views: 97

Answers (1)

tmfmnk
tmfmnk

Reputation: 39858

Turning my comment into a post. Using dplyr, you can do:

data %>% 
 group_by(loc_id) %>% 
 mutate(y = y + ((rank - 1) * 0.00075))

Upvotes: 2

Related Questions