2

I am a new R user and having some difficulty when trying to rename certain records in a column.

My data have columns named classcode and fish_tl, among others. Classcode is a character value, fish_tl is numeric.

When classcode='OCAL' and fish_tl<20, I need to rename that value of classcode so that it is now "OCALYOY". I don't want to change any of the other records in classcode.

I'm running the following code:

data$classcode<-ifelse(data$classcode=='OCAL'& data$fish_tl<20,
                              'OCALYOY',data$classcode)

My problem seems to be with the "else" aspect: the code runs fine, and returns 'OCALYOY' as expected, but the other values of classcode have now been converted to numeric (although when I look at the mode of that field, it still returns as "character").

What am I doing wrong? Thanks very much!

2 Answers2

0

You can make the else part as.character(data$classcode). ifelse has some odd semantics with regard to the classes of the arguments, and it is turning your factor into it's underlying numeric representation. as.character will keep it as a character value.

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188
0

You may be getting tripped up in a factor vs character issue, though you point out that R thinks it's character. Regardless, wrapping as.character() around your code seems to fix the problem for me:

> ifelse(data$classcode=='OCAL'& data$fish_tl<20,
+        'OCALYOY',as.character(data$classcode))
#-----
 [1] "BFRE"    "BFRE"    "BFRE"    "HARG"    "OCALYOY" "OYT"     "OYT"     "PFUR"   
 [9] "SPAU"    "BFRE"    "OCALYOY" "OCAL" 

If this isn't it, can you make your question reproducible by adding the output of dput() to your question instead of the text representation?

Community
  • 1
  • 1
Chase
  • 67,710
  • 18
  • 144
  • 161
  • Thanks--that fixed it. Sorry about the text representation...still trying to figure out how to post. I'll use dput() next time. – user1729954 Oct 08 '12 at 21:54