-3

I am working on a survey document on CVS by R. Before the analysis, I want to reverse the coding of some items on 4 likert scale. To turn 1 to 4, 2 to 3, 3 to 2, and 4 to 1.

Any ideas on how to do that?

sebgok
  • 15
  • 2

1 Answers1

1

One option is to subtract from 4 (assuming these are the only values)

4- v1 + 1
#[1] 2 2 1 2 3 2 4 3 1 3 3 4 1 4 1 2 1 4 4 1

comparing with original vector

v1
#[1] 3 3 4 3 2 3 1 2 4 2 2 1 4 1 4 3 4 1 1 4

The same code can be applied on matrix. After subset the columns [, 5:10], do the calculation, and update by assignment (<-) for the same columns

m1[, 5:10] <- 4 - m1[, 5:10] + 1

If there are more elements and want to only change values 1 to 4

i1 <- v1n %in% 1:4
v2 <- v1n
v2[i1] <- 4- v2[i1] + 1

data

set.seed(24)
v1 <- sample(1:4, 20, replace = TRUE)
set.seed(48)
v1n <- sample(1:9, 20, replace = TRUE)

set.seed(24)
m1 <- matrix(sample(1:4, 20 * 10, replace = TRUE), ncol = 10)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you, Akrun. I was not clear at my question: I want to to this on a matrix, though. For example on a matrix from column 5 to column 10, I want to reverse all item values. – sebgok Nov 29 '19 at 22:44
  • @sebgok You can use the same code and assign `m1[, 5:10] <- 4 - m1[, 5:10] + 1` – akrun Nov 29 '19 at 22:47