[英]Reverse score a vector
I have numeric vectors, such as c(1, 2, 3, 3, 2, 1, 3)
or c(1, 4, 1, 4, 4, 1)
, and I would like to keep individual element's position, but swap/reverse the value, so that we get c(3, 2, 1, 1, 2, 3, 1)
, c(4, 1, 4, 1, 1, 4)
respectively. 我有数字向量,如
c(1, 2, 3, 3, 2, 1, 3)
或c(1, 4, 1, 4, 4, 1)
,我想保持单个元素的位置,但交换/反转该值,这样我们分别得到c(3, 2, 1, 1, 2, 3, 1)
, c(4, 1, 4, 1, 1, 4)
。
To achieve that, I came up with a rather rough and ugly code below with lots of debugging and patching... 为了达到这个目的,我在下面提出了一个相当粗糙和丑陋的代码,并进行了大量的调试和修补......
blah <- c(1, 4, 1, 4, 4, 1, 3)
blah.uniq <- sort(unique(blah))
blah.uniq.len <- length(blah.uniq)
j <- 1
end <- ceiling(blah.uniq.len / 2)
if(end == 1) {end <- 2} # special case like c(1,4,1), should get c(4,1,4)
for(i in blah.uniq.len:end) {
x <- blah == blah.uniq[i]
y <- blah == blah.uniq[j]
blah[x] <- blah.uniq[j]
blah[y] <- blah.uniq[i]
j = j + 1
}
blah
Is there an easier way to do this? 有更简单的方法吗?
I think you're trying to reverse score. 我想你正试图扭转得分。 The algorithm is (1 + max(x_i)) - x_i
算法是(1 + max(x_i)) - x_i
so... 所以...
x <- c(1, 2, 3, 3, 2, 1, 3)
y <- c(1, 4, 1, 4, 4, 1)
(max(x, na.rm=T) + 1) - x
(max(y, na.rm=T) + 1) - y
yielding: 收益:
> (max(x, na.rm=T) + 1) - x
[1] 3 2 1 1 2 3 1
> (max(y, na.rm=T) + 1) - y
[1] 4 1 4 1 1 4
Per the OP's comment: 根据OP的评论:
rev.score <- function(x) {
h <- unique(x)
a <- seq(min(h, na.rm=T), max(h, na.rm=T))
b <- rev(a)
dat <- data.frame(a, b)
dat[match(x, dat[, 'a']), 2]
}
x <- c(1, 2, 3, 3, 2, 1, 3)
rev.score(x)
y <- c(1, 4, 1, 4, 4, 1)
rev.score(y)
z <- c(1, 5, 10, -3, -5, 2)
rev.score(z)
Congratulations! 恭喜! You might have finally found a use for
factor
s , I was still looking for one :-) 你可能终于找到了
factor
s的用途,我还在寻找一个:-)
x <- c(1, 2, 3, 3, 2, 1, 3)
# [1] 1 2 3 3 2 1 3
y <- factor(x)
# [1] 1 2 3 3 2 1 3
# Levels: 1 2 3
levels(y) <- rev(levels(y))
# [1] 3 2 1 1 2 3 1
# Levels: 3 2 1
Built on that idea, here is a function that returns an object with the same class as the input: 基于这个想法,这是一个函数,它返回一个与输入具有相同类的对象:
swap <- function(x) {
f <- factor(x)
y <- rev(levels(f))[f]
class(y) <- class(x)
return(y)
}
swap(c(1, 2, 3, 3, 2, 1, 3))
# [1] 3 2 1 1 2 3 1
swap(c(1, 4, 1, 4, 4, 1))
# [1] 4 1 4 1 1 4
A possible generalisable function. 可能的一般功能。
revscore <- function(x) {
rx <- min(x):max(x)
rev(rx)[sapply(1:length(x), function(y) match(x[y],rx))]
}
x1 <- c(-3,-1,0,-2,3,2,1)
x2 <- c(-1,0,1,2)
x3 <- 1:7
Some testing: 一些测试:
> x1
[1] -3 -1 0 -2 3 2 1
> revscore(x1)
[1] 3 1 0 2 -3 -2 -1
> x2
[1] -1 0 1 2
> revscore(x2)
[1] 2 1 0 -1
> x3
[1] 1 2 3 4 5 6 7
> revscore(x3)
[1] 7 6 5 4 3 2 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.