-1

I have a discrete variable with scores from 1-3. I would like to change it so 1=2, 2=1, 3=3.

I have tried

recode(Data$GEB43, "c(1=2; 2=1; 3=3")

But that doesn't work.

I know this is an overly stupid question that can be solved in excel within seconds but trying to learn how to do basics like this in R.

s_baldur
  • 29,441
  • 4
  • 36
  • 69
A Soutter
  • 61
  • 1
  • 1
  • 7
  • 1
    You said that the variable is continuous. Are you sure? Is 1.2 a possible value? If so, how it should be decoded? – nicola Feb 27 '20 at 08:43
  • Yes I'm sure. 1.2 is not a value. The values are 1, 2, or 3. I want scores of 1 to become a score of 2, and scores of 2 to become a 1 – A Soutter Feb 27 '20 at 08:44
  • 1
    So it's not a continuous variable. It's discrete. Just try `c(2,1,3)[data$GEB43]`. – nicola Feb 27 '20 at 08:45
  • Is it character, numeric/double, integer, or factor. That is `class(Data$GEB43)`? – s_baldur Feb 27 '20 at 08:52

2 Answers2

3

We should always provide a minimal reproducible example:

df <- data.frame(x=c(1,1,2,2,3,3))

You didn't specifiy the package for recode so I assumed dplyr. ?dplyr::recode tells us how the arguments should be passed to the function. In the original question "c(1=2; 2=1; 3=3" is a string (i.e. not an R expression but a character string "c(1=2; 2=1; 3=3"). To make it an R expression we have to get rid of the double quotes and replace the ; with ,. Additionally, we need a closing bracket i.e. c(1=2, 2=1, 3=3). But still, as ?dplyr::recode tells us, this is not the way to pass this information to recode:

Solution using dplyr::recode:

dplyr::recode(df$x, "1"=2, "2"=1, "3"=3)

Returns:

[1] 2 2 1 1 3 3
dario
  • 6,415
  • 2
  • 12
  • 26
1

Assuming, you mean dplyr::recode, the syntax is

recode(.x, ..., .default = NULL, .missing = NULL)

From the documentation it says

.x - A vector to modify

... - Replacements. For character and factor .x, these should be named and replacement is based only on their name. For numeric .x, these can be named or not. If not named, the replacement is done based on position i.e. .x represents positions to look for in replacements

So when you have numeric value you can replace based on position directly

recode(1:3, 2, 1, 3)
#[1] 2 1 3
Community
  • 1
  • 1
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213