反向得分矢量

Ant*_*ony 5 r numeric

我有数字载体,如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)分别.

为了达到这个目的,我在下面提出了一个相当粗糙和丑陋的代码,并进行了大量的调试和修补......

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
Run Code Online (Sandbox Code Playgroud)

有更简单的方法吗?

Tyl*_*ker 11

我想你正试图扭转得分.算法是(1 + max(x_i)) - x_i

所以...

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
Run Code Online (Sandbox Code Playgroud)

收益:

> (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
Run Code Online (Sandbox Code Playgroud)

根据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)
Run Code Online (Sandbox Code Playgroud)

  • 实际上,该算法是心理测量学中的经典,它很简单,适合你的模糊帖子.Occam的剃刀说这项工作最简单.如果您有角落情况,请尝试考虑它们并在您的问题或您给出的示例代码中指出它."实际上"是一个加载的单词,面对有人试图提供帮助.请参阅上面的编辑. (3认同)

flo*_*del 6

恭喜!你可能终于找到了factors 的用途,我还在寻找一个:-)

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
Run Code Online (Sandbox Code Playgroud)

基于这个想法,这是一个函数,它返回一个与输入具有相同类的对象:

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
Run Code Online (Sandbox Code Playgroud)


the*_*ail 5

可能的一般功能.

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
Run Code Online (Sandbox Code Playgroud)

一些测试:

> 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
Run Code Online (Sandbox Code Playgroud)