0

I have data like this

> data

satface1         satface2               satface3         satface 4 ... satface10
Agree            Disagree               Neutral
Disagree         Strongly Disagree      Strongly Agree
Agree            Disagree               Agree
Neutral          Agree                  Neutral
Strongly Agree   Neutral                Disagree

and I want to recode

Strongly Disagree = 1, Disagree = 2, Neutral = 3, Agree = 4, Disagree = 5 

and make them as new columns (name satface1_re, satface2_re....) How can I do that?

> data

satface1         satface2               satface3       (satface4...10)  satface1_re satface2_re satface3_re
Agree            Disagree               Neutral                          4           2           3 
Disagree         Strongly Disagree      Strongly Agree                   2           1           5
Agree            Disagree               Agree                            4           2           4
Neutral          Agree                  Neutral                          3           4           3
Strongly Agree   Neutral                Disagree                         5           3           2
Yubin
  • 7
  • 1

1 Answers1

2

An option is to recode with factor. Specify the levels in the order required, and coerce to numeric with as.integer in across and add new column by altering the .names

library(dplyr) # 1.0.0
lvls <- c("Strongly Disagree", "Disagree", "Neutral", "Agree", "Strongly Agree") 
data1 <- data %>%
     mutate(across(starts_with('satface'),
        ~ as.integer(factor(., levels = lvls)), .names = "{col}_re"))

Or using recode with a named vector

data %>% 
   mutate(across(starts_with('satface'),
     ~ recode(., !!! setNames(1:5, lvls)), .names = "{col}_re"))

data

data <- structure(list(satface1 = c("Agree", "Disagree", "Agree", "Neutral", 
"Strongly Agree"), satface2 = c("Disagree", "Strongly Disagree", 
"Disagree", "Agree", "Neutral"), satface3 = c("Neutral", "Strongly Agree", 
"Agree", "Neutral", "Disagree")), class = "data.frame", row.names = c(NA, 
-5L))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • I was trying to play with it, and I did `recode(data, "Agree" = 1)` for a short trial, but I was getting errors. – Daniel_j_iii Aug 01 '20 at 01:54
  • @DanielJachetta you can try the updated code. In your code, `recode` is applied to the whole data. where I applied on each column i..e vector – akrun Aug 01 '20 at 01:55
  • @DanielJachetta or use `data %>% mutate(across(starts_with('satface'), ~ recode(., `Strongly Disagree` = 1, Disagree = 2, Neutral = 3)))` – akrun Aug 01 '20 at 01:58