Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replicate SPSS recode function in R?

Tags:

r

spss

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?

like image 990
Diegoal Avatar asked Jun 17 '26 03:06

Diegoal


2 Answers

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
like image 167
Tyler Rinker Avatar answered Jun 18 '26 22:06

Tyler Rinker


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)
like image 34
djhurio Avatar answered Jun 18 '26 20:06

djhurio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!