Reputation: 51
Hi I'm trying to determine the change in ordering of two lists in R.
e.g. Comparing rankings of tennis players from two different months.
Feb <- c("A", "B", "C", "D")
Mar <- c("D", "B", "C", "A")
orderChange(Feb, Mar)
I would like to get a result which shows the difference in ordering/ranking.
(-3, 0, 0, 3)
I've tried which() but that only tells me whether an element is present and doesn't compare the ordering.
which(Mar %in% Feb)
[1] 1 2 3 4
Upvotes: 0
Views: 176
Reputation: 39667
You can use seq_along
and subtract match
.
Feb <- c("A", "B", "C", "D")
Mar <- c("D", "B", "C", "A")
Apr <- c("C", "B", "D", "A")
seq_along(Feb) - match(Feb, Mar)
#[1] -3 0 0 3
seq_along(Feb) - match(Feb, Apr)
#[1] -3 0 2 1
and can pack this in a function if needed.
orderChange <- function(x, y) seq_along(x) - match(x, y)
Upvotes: 3