[R] Recoding lists of categories of a variable

MACDOUGALL Margaret Margaret.MacDougall at ed.ac.uk
Mon Oct 10 22:38:29 CEST 2016

Thank you for the valued suggestions in response to my query.


The University of Edinburgh is a charitable body, registered in
Scotland, with registration number SC005336.

-----Original Message-----
From: Fox, John [mailto:jfox at mcmaster.ca] 
Sent: 10 October 2016 20:32
To: MACDOUGALL Margaret <Margaret.MacDougall at ed.ac.uk>
Cc: r-help at r-project.org
Subject: RE: Recoding lists of categories of a variable

Dear Margaret,

You've had one suggestion of an alternative for recoding variables, but in addition your code is in error (see below).

> -----Original Message-----
> From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of 
> Sent: Monday, October 10, 2016 10:56 AM
> To: r-help at r-project.org
> Subject: [R] Recoding lists of categories of a variable
> Hello
> The R code
> mydata$newvar[oldvar = "topic1"] <- "parenttopic"

That should be

   mydata$newvar[oldvar == "topic1"] <- "parenttopic"

Moreover, the code assumes that oldvar is visible, which may not be the case if it lives in mydata and mydata isn't attach()ed.


John Fox, Professor
McMaster University
Hamilton, Ontario, Canada
Web: socserv.mcmaster.ca/jfox

> is intended to recode the category 'topic 1' of the old  varaible 
> 'oldvar' a new category label 'parenttopic' by defining the new 
> variable 'newvar'.
> Is there a convenient way to edit this code to allow me to recode a 
> list of categories 'topic 1', 'topic 9' and 'topic 14', say, of the 
> the old variable 'oldvar' as 'parenttopic' by means of the new 
> variable 'newvar', while also mapping system missing values to system 
> missing values?
> Thanks in advance
> Best wishes
> Margaret

More information about the R-help mailing list