[R] Recoding lists of categories of a variable

Jim Lemon drjimlemon at gmail.com
Mon Oct 10 23:08:07 CEST 2016


Hi Margaret,
This may be a misunderstanding of your request, but what about:

mydata<-data.frame(oldvar=paste("topic",sample(1:9,20,TRUE),sep=""))
mydata$newvar<-sapply(mydata$oldvar,gsub,"topic.","parenttopic")

Jim


On Tue, Oct 11, 2016 at 1:56 AM, MACDOUGALL Margaret
<Margaret.MacDougall at ed.ac.uk> wrote:
> Hello
>
> The R code
> mydata$newvar[oldvar = "topic1"] <- "parenttopic"
>
> 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
>
>
> The University of Edinburgh is a charitable body, registered in
> Scotland, with registration number SC005336.
>
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list