0

I have a big data frame from a survey. There is some statements where I need to use revere coding, hence I need to change values in few columns. I have tried below code (where x represents the column where I want to make the changes)

df$x <- replace( df$x, 1=7, 2=6, 3=5, 5=3, 6=2, 7=1) 

But this did not work. Every help is much appreciated.

4 Answers 4

1

If your column has only 1-7 values you can subtract those values from 8 to reverse the values.

set.seed(123) df <- data.frame(x = sample(7, 10, replace = TRUE)) df$y <- 8 - df$x #Or maybe more general #df$y <- max(df$x) + 1 - df$x df # x y #1 7 1 #2 7 1 #3 3 5 #4 6 2 #5 3 5 #6 2 6 #7 2 6 #8 6 2 #9 3 5 #10 5 3 
Sign up to request clarification or add additional context in comments.

Comments

1

You could try case_when from package dplyr. The syntax is very clean.

library(dplyr) df %>% mutate(x=case_when( x == 1 ~ 7, x == 2 ~ 6, x == 3 ~ 5, x == 6 ~ 2, x == 7 ~ 1, TRUE ~ as.numeric(x) )) 

DATA

set.seed(1) df <- data.frame(x = sample(7, 10, replace = TRUE)) df 

The solution above overwrites the varaible x. To compare result, I created a new_x variable with the replaced data:

df %>% mutate(new_x=case_when( x == 1 ~ 7, x == 2 ~ 6, x == 3 ~ 5, x == 6 ~ 2, x == 7 ~ 1, TRUE ~ as.numeric(x) )) x new_x 1 1 7 2 4 4 3 7 1 4 1 7 5 2 6 6 5 5 7 7 1 8 3 5 9 6 2 10 2 6 

Comments

1

One way you can replace values is using which:

df$x[which(df$x=1)] <- 7 # this replaces 1 with 7 

Another way is to use ifelse:

df$x <- ifelse(df$x == 1,7,ifelse(df$x == 2,6,ifelse....)) # replaces 1 with 7, 2 with 6 and so on.. 

Comments

0

An option with which.max

library(dplyr) df %>% mutate(y = x[which.max(x)] - x + 1) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.