3

I am having problem with the following codes (I'm a beginner, so please go easy on me):

COW$id<- (COW$tcode1*1000 + COW$tcode2)
COW$id<- (COW$tcode2*1000 + COW$tcode1)

I want the first line of code to be executed on the condition that the value of tcode1 (a variable in COW dataframe) is less than tcode2 (tcode1 < tcode2), and I want the second line of code to be executed if tcode1 is greater than tcode2 (tcode1 > tcode2). The end result I am looking for is a single column "ID" in my dataframe, on the basis of the conditions above. Does anyone know how to achieve this?

Andre Silva
  • 4,782
  • 9
  • 52
  • 65
Freddie1
  • 35
  • 4

1 Answers1

4
COW = data.frame(tcode1=c(5,7,18,9),tcode2=c(4,15,8,10))
head(COW)

  tcode1 tcode2
      5      4
      7     15
     18      8
      9     10

id = ifelse(COW$tcode1<COW$tcode2,
            COW$tcode1*1000 + COW$tcode2,
            COW$tcode2*1000 + COW$tcode1)

COW = data.frame(id=id,COW)
head(COW)

  id tcode1 tcode2
4005      5      4
7015      7     15
8018     18      8
9010      9     10
Andre Silva
  • 4,782
  • 9
  • 52
  • 65
  • @Freddie1, this [post](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) might help you to improve your R questions on Stack Overflow in a future opportunity. – Andre Silva Dec 05 '14 at 13:48
  • There's always the alternative (but not necessarily faster) use of logicals: `id <- COW$tcode1*(1+999*(COW$tcode1=COW$tcode2)) ` :-) – Carl Witthoft Dec 05 '14 at 14:20
  • @CarlWitthoft, not sure I followed your suggestion. I ran the code with the example in the answer and it returned `numeric(0)`?. Anyway, I was trying to provide a step by step to help the OP who is beginning in R (in fact, I'm also a beginner). – Andre Silva Dec 05 '14 at 14:27
  • 1
    probably because of my typo with a capital "T" .Try it with that fixed; I got `[1] 4005 7015 8018 9010` – Carl Witthoft Dec 05 '14 at 15:29
  • @AndreSilva thank you so much for your help. It worked. I was a bit hesitant in asking, but I'm glad i did! thanks again – Freddie1 Dec 05 '14 at 16:49