How to recode (and vice versa) variables in columns with dplyr

I collect R again after last using it in 2013. I'm used to using dplyr, but I have a problem with a simple task. I have a table that looks like

Participant Q1       Q2      Q3     Q4       Q5
1           agree  neutral   NA    Disagree  Agree
2           neutral agree    NA     NA       NA

My goal

   Participant Q1       Q2      Q3     Q4       Q5
    1           3       2       NA      1       3
    2           2       1       NA     NA       NA

I want to be able to change the categorical value to a numeric value for Q1: Q5 columns, but all the examples that I see when using recode for dplyr work for rows and columns. (I might have missed something in the examples). Then I want you to be able to select the column Q1 and Q2 and the reverse code.

I'm trying to learn how to do this in dplyr, if possible

thank

+3
source share
2 answers

base R - . vector ('v1'),

v1 <- setNames(c(1:3, 3), c("Disagree", "neutral", "agree", "Agree"))
df1[-1] <- lapply(df1[-1], function(x) if(any(!is.na(x))) v1[x] else NA)
df1 
#  Participant Q1 Q2 Q3 Q4 Q5
#1           1  3  2 NA  1  3
#2           2  2  3 NA NA NA

df1 <- structure(list(Participant = 1:2, Q1 = c("agree", "neutral"), 
Q2 = c("neutral", "agree"), Q3 = c(NA, NA), Q4 = c("Disagree", 
NA), Q5 = c("Agree", NA)), .Names = c("Participant", "Q1", 
"Q2", "Q3", "Q4", "Q5"), class = "data.frame", row.names = c(NA, -2L))
0

dplyr recode. :

# Generate a dataframe to match yours

df <- data.frame(
  participant = c(1,2),
  Q1 = c("agree", "neutral"),
  Q2 = c("neutral", "agree"),
  Q3 = c(NA,NA),
  Q4 = c("Disagree", NA),
  Q5 = c("Agree", NA)
)

# Use recode to recode the data

df_recode <- df %>%
  mutate(Q1 = recode(Q1, "agree" = 3, "neutral" = 2),
         Q2 = recode(Q2, "neutral" = 2, "agree" = 1),
         Q4 = recode(Q4, "Disagree" = 1),
         Q5 = recode(Q5, "Agree" = 3)
  )

.default .missing , , NAs, .

+4

Source: https://habr.com/ru/post/1650430/


All Articles