Search code examples
rvariablesdatasetrecode

Recode the value of a variable given the value of another one


I am using a dataset in which there is a mistake in the way the answers for a given country are coded. Let's call my first variable my.data$country_year and the second one my.data$attitude. A table of the two gives the following output:

table(my.data$country_year, my.data$attitude)

       (1) Very Suitable (2) Suitable (3) Somewhat Suitable (4) Not Suitable                      
Yemen.2006    101            142             1192                       0
Lebanon.2007   13           14                    60                  1063
Yemen.2007       49          113                   122                  248
Palestine.2008    131          653                   387                2093

The table in question has a lot of countries which I omitted in this example.What I want to do is to ask R to do the following in my original dataset while keeping the observations for all other countries:

for my.data$country="Yemen.2006" & my.data$attitude="(3) Somewhat Suitable", "(4) Not Suitable.

for my.data$country="Yemen.2006" & my.data$attitude="(2) Suitable", "(3) Somewhat Suitable"

In other words, I would like to move to the right the second and third values of the attitude variable for the survey conducted in Yemen in 2006, without creating a new variable. I would like the result to be the following

 (1) Very Suitable (2) Suitable (3) Somewhat Suitable (4) Not Suitable                      
Yemen.2006    101            0                   142                 1192                       
Lebanon.2007   13            14                    60                  1063
Yemen.2007       49          113                   122                  248
Palestine.2008    131          653                   387                2093

Solution

  • Ok, so thank you everybody, I based myself on your answers in order to find the solution. I created a subset of my.data with less variables and this time the within function worked without errors. Only it's r2evans' script that worked best, as follows

    my.data2 <- within(my.data2, {attitude[country_year=="Yemen.2006" & 
    attitude=="(3) Somewhat Suitable"] <- "(4) Not Suitable At All" })
    
    my.data2 <- within(my.data2, {attitude[country_year=="Yemen.2006" & 
    attitude=="(2) Suitable"] <- "(3) Somewhat Suitable" })
    

    Cheers and thanks for your time and help!