1

enter code hereI have a SPSS data, loaded using haven package, which I need to change values 0-4 to 4-0 in several columns called here as "tss" in the data psychophobia (psychophobia$tss1, psychophobia$tss2...), creating a new column as recodtss... additionally, there are several NAs data.

enter image description here

I´ve tried this code:

old <- 0:4
new <- c(4:0)
psychophobia$Recodtss01 <- psychophobia$tss01[psychophobia$tss01 %in% old] <-new[match(psychophobia$tss01,old,nomatch = "NA")]
psychophobia$Recodtss02 <- psychophobia$tss01[psychophobia$tss02 %in% old] <-new[match(psychophobia$tss02,old,nomatch = "NA")]

The problem is that the current output is

psychophobia$tss01 1 4 1 1 NA NA 3 2 0 1

psychophobia$Recodtss01 1 4 1 1 NA 3 2 0 1 2

Can anyone help to understand why? :)

Jontexas
  • 121
  • 8
  • 2
    Please provide a minimal reproducible data. You could copy/paste the output of `dput(psychophobia)` to your post. – Darren Tsai Jul 21 '22 at 13:35
  • tss05 = structure(c(3, 1, 1, 1, 4, 1, 2, 3, 3, 3, 3, 3, 3, 0, 4, 1, 0, 3, 3, 1, 4, 2, 1, 2, 4, 3, 3, 3, 3, 3, 3, 3, 1, 3, 1, 1, 3, NA, 3, 3, NA, 4, 3, 1, 1, 3, 3, 3, 3, 3, 3, 1, 1, 1, 2, 1, 0, 1, 1, 0, 2, 0, 3, 4, 3, 0, 1, 3, 2, 4, 2, 2, 2, 2, 3), label = "tratamento psicologico", format.spss = "F8.2", labels = c(`Discordo fortemente` = 0, Discordo = 1, `Não concordo nem discordo` = 2, Concordo = 3, `Concordo fortemente` = 4), class = c("haven_labelled", "vctrs_vctr", "double")) – Jontexas Jul 21 '22 at 13:38
  • I´ve updated the post with a small table of the dataframe – Jontexas Jul 21 '22 at 13:48
  • 1
    The simplest way to convert 0:4 to 4:0 is `Recodtss05 <- 4 - tss05`, although this drops the information of labels. – Darren Tsai Jul 21 '22 at 14:20
  • I cannot believe it is that simple... thank you soo much – Jontexas Jul 21 '22 at 14:28
  • @DarrenTsai how can I create a loop for this? for (i in 01:28){ psychophobia$Recodtss[i] <- 4 - psychophobia$tss[i]} – Jontexas Jul 21 '22 at 14:58
  • `for (i in 1:28) { psychophobia[[sprintf("Recodtss%02d", i)]] <- 4 - psychophobia[[sprintf("tss%02d", i)]] }` – Darren Tsai Jul 21 '22 at 15:32

1 Answers1

0

If you are familiar with SPSS, the package https://strengejacke.github.io/sjmisc/reference/rec.html might help you. The syntax is more elaborate, but safe and easy to read.

table(rec(psychophobia$Recodtss01, rec = "1=4;2=3;3=2;4=1;NA=9"), useNA = "always")

or with dplyr

psychophobia %>%
   mutate(Recodetss01 = sjmisc::rec(Recodetss01, rec = "1=4;2=3;3=2;4=1;NA=9"))