Executing two separate codes based on conditions
I am having a problem with the following codes (I am a beginner, so please feel free to 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 assuming the value tcode1
(variable in the COW data frame) 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'm looking for is a single "ID" column in my dataframe based on the above conditions. Does anyone know how to achieve this?
+3
source to share
1 answer
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
+4
source to share