[R] Recoding lists of categories of a variable

Bert Gunter bgunter.4567 at gmail.com
Mon Oct 10 19:39:03 CEST 2016


Well, I think that's kind of overkill.

Assuming "oldvar" is a factor in the data frame mydata, then the
following shows how to do it:

> set.seed(27)
> d <- data.frame(a = sample(c(letters[1:3],NA),15,replace = TRUE))
> d
      a
1  <NA>
2     a
3  <NA>
4     b
5     a
6     b
7     a
8     a
9     a
10    a
11    c
12 <NA>
13    c
14    c
15 <NA>


> d$b <- factor(d$a,labels = LETTERS[3:1])
> d
      a    b
1  <NA> <NA>
2     a    C
3  <NA> <NA>
4     b    B
5     a    C
6     b    B
7     a    C
8     a    C
9     a    C
10    a    C
11    c    A
12 <NA> <NA>
13    c    A
14    c    A
15 <NA> <NA>


See ?factor for details.

Incidentally note that in the OP's post,

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

is completely incorrect; it should probably be:

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

This suggests to me that the OP would probably find it useful to spend
some time with one or more of the many good R tutorials on the web.

Cheers,
Bert











Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Mon, Oct 10, 2016 at 9:08 AM, S Ellison <S.Ellison at lgcgroup.com> wrote:
>> 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?
>
> You could look at 'recode()' in the car package.
>
> There's a fair description of other options at http://www.uni-kiel.de/psychologie/rexrepos/posts/recode.html
>
> S Ellison
>
>
>
>
> *******************************************************************
> This email and any attachments are confidential. Any u...{{dropped:8}}



More information about the R-help mailing list