3
votes

Aim is to simulate the SPSS recode procedure in R. The copy-command is hard to translate.

In SPSS I have code as

RECODE A (1,2 = 1) (3,4 = copy) (8 thru hi = 3) (else = 1) into B.

Applied over A which looks like

A <- c(1,2,3,4,5,NA,7,8,9)

i get the following (SPSS) result:

A = 1,1,3,4,1,1,1,3,3

In R a similar code would look like this:

B <- Recode(A, recodes = ("c(1,2) = 1; c(3,4) = c(3,4); c(8,9) = 3; else = 1"), as.numeric.result = TRUE)

A = 1,1,3,4,1,1,1,3,3

The general Problem is to indicate the Values in the SPSS-copy statement. Here I wrote c(3,4) = c(3,4) - of course, it doesn´t work.

In SPSS also exists the possibility to say else = copy what returns the same output as R do.

Does anyone have a R function that works in the same way as SPSS?

4

4 Answers

2
votes

use the levels function. Here's and example with a built in data set:

InsectSprays
levels(InsectSprays$spray)<-list(new1=c("A","C"),YEPS=c("B","D","E"),LASTLY="F") 
InsectSprays

use this to reset the data set:

InsectSprays <- datasets::InsectSprays
2
votes

You can combine ifelse and car::recode to achieve the result you want.

library(car)
A <- c(1,2,3,4,5,NA,7,8,9)
B <- ifelse(A %in% c(3,4), A, recode(A, "c(1,2) = 1; 8:hi = 3; else = 1"))
cbind(A, B)
1
votes

You might want to check out the car package. Unfortunately, there is no "copy" functionality available.

library(car)
?recode
A <- c(1,2,3,4,5,NA,7,8,9)
B <- recode(A, "c(1,2) = 1; 3 = 3; 4 = 4; 8:hi = 3; else = 1")
B

## SPSS result: A = 1,1,3,4,1,1,1,3,3
## > B
## [1] 1 1 3 4 1 1 1 3 3
## > 
0
votes
library(expss)
a = c(1,2,3,4,5,NA,7,8,9)
# '%into%' supports multi-value assignment, eg: ... %into% (a1 %to% a3)
recode(a, 1:2 ~ 1, 3:4 ~ copy, 8 %thru% hi ~ 3, other ~ 1) %into% b
b
# 1 1 3 4 1 1 1 3 3

or, with standard R assignment:

b = recode(a, 1:2 ~ 1, 3:4 ~ copy, 8 %thru% hi ~ 3, other ~ 1)
b
# 1 1 3 4 1 1 1 3 3