In psychology variables often need to be recoded into reverse order in cases that items are negatively worded. So it can be ensured that a high value indicate the same type of response on every item. Let's say we have a Likert scale from 1 to 5 and we want to recode the variable so that a 5 becomes a 1, 4 a 2 and so on.

RevCode(x, ...)

Arguments

x

a numerical or logical vector, or a factor.

...

the dots are sent to min/max, such as possibly to remove NAs before reversing numeric values.

Details

The function recodes based on:

min(x, na.rm=TRUE) + max(x, na.rm=TRUE) - x

Value

the recoded vector

Author

Andri Signorell <andri@signorell.net>

See also

Examples

x <- 1:5
data.frame(x, rev_num=RevCode(x), rev_fac=RevCode(factor(x)))
#>   x rev_num rev_fac
#> 1 1       5       5
#> 2 2       4       4
#> 3 3       3       3
#> 4 4       2       2
#> 5 5       1       1

s <- c(3,4,2,7,4,9,NA,10) 
RevCode(factor(s, levels=1:10))
#> [1] 8    7    9    4    7    2    <NA> 1   
#> Levels: 1 2 3 4 5 6 7 8 9 10

i <- c(1,0,0,0,1,1)
cbind(i, RevCode(i))
#>      i  
#> [1,] 1 0
#> [2,] 0 1
#> [3,] 0 1
#> [4,] 0 1
#> [5,] 1 0
#> [6,] 1 0

k <- as.logical(c(1,0,0,0,1,1))
cbind(k, RevCode(k))
#>          k      
#> [1,]  TRUE FALSE
#> [2,] FALSE  TRUE
#> [3,] FALSE  TRUE
#> [4,] FALSE  TRUE
#> [5,]  TRUE FALSE
#> [6,]  TRUE FALSE

x <- factor(sample(letters[1:5], 10, replace = TRUE))
RevCode(x)
#>  [1] b a b c d b c c a d
#> Levels: a b c d

# we want to set the level 5 to NA before reversing
RevCode(factor(NAIf(x, "e")))
#>  [1] b a b c d b c c a d
#> Levels: a b c d