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?
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
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)