I'm new to the forum and relatively new to R.
I'm currently manipulating my data. The data are placed in a DataFrame. I'd like to compare the values in each row of column 'Prime' to each corresponding row of column 'target'. If the values match I want to add the value '1' to the corresponding row in column 'Match' and if they don't match add a '0'.
Below is an example of the columns and the solution under column 'Match'
Prime Target Match
faces0 faces0 1
faces0 faces0 1
houses1 faces0 0
I toyed around using ifelse and identical but it compares the objects as a whole and not the individual and corresponding rows.
Can anyone suggest a means of comparing Prime and Target while assigning a value to Match dependant on a match being made or not?
Thanks very much for your time.
This is a straight logical test, so if you compare the two columns for equality, you will get TRUE/FALSE, which can easily be converted to 1/0 with as.numeric(). Depending on how your columns are coded, they may need to be converted to character before the comparison:
dat$Match <- as.numeric(dat$Prime == dat$Target)
dat$Match
# [1] 1 1 0
You can use ifelse or matchbut need to convert to numeric before that. Here is the solution.
mydata<-structure(list(Prime = structure(c(1L, 1L, 2L), .Label = c("faces0",
"houses1"), class = "factor"), Target = structure(c(1L, 1L, 1L
), .Label = "faces0", class = "factor"), Match = c(1, 1, 0)), .Names = c("Prime",
"Target", "Match"), row.names = c(NA, -3L), class = "data.frame")
> mydata$Match<-with(mydata,ifelse(as.numeric(Prime)==as.numeric(Target),1,0))
> mydata
Prime Target Match
1 faces0 faces0 1
2 faces0 faces0 1
3 houses1 faces0 0
mydata$Match<-with(mydata,match(as.numeric(Prime),as.numeric(Target),nomatch=0))
> mydata
Prime Target Match
1 faces0 faces0 1
2 faces0 faces0 1
3 houses1 faces0 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With