Recoding multiple values in R?

Viewed 51

This is my first post so I'd be grateful for any assistance!

I'm recoding a variable in SPSS:

RECODE income(60, 61, 62, 63 = 200) INTO income_2.
EXECUTE.

CROSSTABS income_2 by income.

So far I've tried the following but I'm not getting any sensible output:

income2019$income_2 <- dplyr::recode(income2019$income_2, '60:63' = 200L)

CrossTable(income2019$income_2, income2019$income)

The crosstable R produces is enormous though - I was assuming it would produce the selected income_2 variable by income variable output.

Thank you :)

2 Answers

Instead of recode, we can replace

income2019$income_2[income2019$income_2 %in% 60:63] <- 200L
income2019 <- data.frame(income = c(60, 61, 62, 63))
income2019$income2 <- income2019$income
income2019$income2[income2019$income2 %in% c(60, 61, 62, 63)] <- 200
income2019
#   income income2
# 1     60     200
# 2     61     200
# 3     62     200
# 4     63     200

# cross tabulate to get frequency
table(income2019$income2, income2019$income)
#     60 61 62 63
# 200  1  1  1  1

You may also use xtabs for cross classifying factors. I am not sure what is your expected output.

xtabs(formula = income2 ~ income, data = income2019)
Related