0

I'm trying to use the replace command to replace factor levels with an associated value. I have 3 variables in my data frame that I'm trying to do this for, and 2 worked perfectly but the third is giving me the following error:

Warning message:

In `[<-.factor`(`*tmp*`, list, value = c(11.76, 13.56, -1.64, -14.04,  :
  invalid factor level, NA generated

Any thoughts why that might be?

data:

       Outfit Wearer Color Score
 1       E      1     R    64
 2       E      2     G    75
 3       E      3     W    71
 4       E      4    Bk    93
 5       E      5    Bu    86
 6       H      1     W    90

Code:

   new.dat$Color <- replace(new.dat$color, col.m[,1], col.m[,3])
   new.dat$Wearer <- replace(new.dat$Wearer, wear.m[,1], wear.m[,3])
   new.dat$Outfit <- replace(new.dat$Outfit, out.m[,1], out.m[,3])

The last one, Outfit is not working. This is what out.m looks like:

     Group.1    x    dev
 1          B 52.0 -14.04
 2          E 77.8  11.76
 3          H 79.6  13.56
 4          J 56.4  -9.64
 5          S 64.4  -1.64

I also tried to 'trim' the vector and matching index in case it was a white space issue, but that didn't help.

Thank you for any thoughts!

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Tiffany
  • 301
  • 1
  • 2
  • 12
  • Because `new.dat$Outfit` is a `factor` with only two levels, you can't replace its values with anything but `E` or `H`. Also, I don't think `replace` is giving you the results you want. Check what you are getting. It is not matching B-to-B, E-to-E etc as you expect. – thelatemail Nov 19 '14 at 01:05
  • new.dat$Outfit has 5 levels, what I have provided is just a subset. The table it is matching to also has 5 levels. I think it may be true that replace is not doing what I think in general. It seems to me that it should work, but maybe I'm misinterpreting the documentation. – Tiffany Nov 19 '14 at 02:15
  • Take a look at `match` maybe instead. As in `out.m$dev[match(new.dat$Outfit,out.m$Group.1)]` – thelatemail Nov 19 '14 at 02:19

1 Answers1

0

I found the following to work from a previous post. I changed how I was thinking about the problem, which is why I hadn't discovered the post previously.

Here's what worked:

 new.dat[,"col.dev"]<-col.m[new.dat[ ,"Color"], "dev"]
 new.dat[,"out.dev"]<-out.m[new.dat[ ,"Outfit"], "dev"]
 new.dat[,"wear.dev"]<-wear.m[new.dat[ ,"Wearer"], "dev"]

from this post:

How to join (merge) data frames (inner, outer, left, right)?

Thank you!

Community
  • 1
  • 1
Tiffany
  • 301
  • 1
  • 2
  • 12