0

Can somebody please help me with a recode from SPSS into R?

SPSS code:

RECODE variable1
(1,2=1)
(3 THRU 8 =2)
(9, 10 =3)
(ELSE = SYSMIS)
INTO variable2

I can create new variables with the different values. However, I'd like it to be in the same variable, as SPSS does.

Many thanks.

  • I think the function `fct_recode()` does what you wnat. See also here: https://r4ds.had.co.nz/factors.html#modifying-factor-levels – AEF Jul 18 '19 at 13:56
  • Could you explain in plain english what you're trying to do. 'Please translate this code for me' questions are generally not well received here. – AkselA Jul 18 '19 at 13:56
  • Possible duplicate of [Cleaning up factor levels (collapsing multiple levels/labels)](https://stackoverflow.com/questions/19410108/cleaning-up-factor-levels-collapsing-multiple-levels-labels) – AkselA Jul 18 '19 at 13:59

2 Answers2

0

I wrote a function that has very similiar coding to the spss code recode. See here

variable1 <- -1:11
recodeR(variable1, c(1, 2, 1), c(3:8, 2), c(9, 10, 3), else_do= "missing")
NA NA  1  1  2  2  2  2  2  2  3  3 NA

This function now works also for other examples. This is how the function is defined

recodeR <- function(vec_in, ..., else_do){
l <- list(...)
# extract the "from" values
from_vec <- unlist(lapply(l, function(x) x[1:(length(x)-1)]))
# extract the "to" values
to_vec <- unlist(lapply(l, function(x) rep(x[length(x)], length(x)-1)))
# plyr is required for mapvalues
require(plyr)
# recode the variable
vec_out <- mapvalues(vec_in, from_vec, to_vec)
# if "missing" is written then all outside the defined range will be missings. 
# Otherwise values outside the defined range stay the same
if(else_do == "missing"){
vec_out <- ifelse(vec_in < min(from_vec, na.rm=T) | vec_in > max(from_vec, na.rm=T), NA, vec_out)
}
# return resulting vector
return(vec_out)}
0
    x <- y<- 1:20
    x
    [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20
    y[x %in% (1:2)] <- 1
    y[x %in% (3:8)] <- 2
    y[x %in% (9:10)] <- 3
    y[!(x %in% (1:10))] <- NA
    y
    [1]  1  1  2  2  2  2  2  2  3  3 NA NA NA NA NA NA NA NA NA NA
Grada Gukovic
  • 1,228
  • 7
  • 13