Hi

I would like to recode data in many columns, making 5 become 1,

making 4 become 2, making 2 become 4, making 1 become 5, to change the

direction of negative-worded item questions. Value of 3 I will leave intact.

How do I do this ?

Thanks.

You can use the `dplyr`

function `mutate_at()`

to do this. `mutate_at()`

is a scoped version of the `mutate()`

function meaning it essentially performs a `mutate()`

on many variables at once.

Say your data is stored in the table `tbl`

and you want to switch the direction of the variables x, y and z.

`mutate_at(tbl, vars(x,y,z), ~6-.)`

Here's my data, here's which variables I want you to do things to, and here's what I want you to do.

That last bit is a "lambda function" and basically just replaces the `.`

with whatever variables you've chosen. The above is the equivalent of writing:

`mutate(tbl, x = 6 - x, y = 6 - y, z = 6 - z)`

If you're familiar with it, the `mutate_at()`

function works with the pipe, much like the `mutate()`

function does:

`tbl %>% mutate_at(vars(x,y,z),~6-.)`

If you have the `magrittr`

package and find the `6-.`

a little hard to read, then the`subtract()`

function will also work in the lambda function:

`tbl %>% mutate_at(vars(x,y,z),~subtract(6,.))`

Also within the `magrittr`

package is the `%<>%`

update pipe which will store the results back into the `tbl`

table variable:

`tbl %<>% mutate_at(vars(x,y,z),~subtract(6,.))`

Which is equivalent to:

`tbl <- tbl %>% mutate_at(vars(x,y,z),~subtract(6,.))`

Thank you for detailed reply. I thought that I should use case_when() to accomplish that.

You *could* use `case_when()`

, however, this would over complicate things. You'd have to write out all five cases (4 flipped and the value 3 remaining the same), whereas mathematically just doing `6-x`

does the same thing

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.