0

I have two datasets: mydata2 and mydata3

Mydata2: 2 columns in it: Destination.DisplayName and Partner.Type

(Partner.Type is based off Destination.DisplayName)

Mydata3: 2 columns in it: If and Then

I need a line of code that tests if Destination.DisplayName is equal to If, and if it is, set partner.type to the value in Then

Right now this is what I have

     mydata2$Partner.Type[  mydata2$Destination.DisplayName %in% mydata3$If] = as.character((mydata3$Then[match(mydata2$Destination.DisplayName, mydata3$If)]))

Does anyone see what is wrong here?

Jon Pop
  • 33
  • 6
  • 2
    Welcome to SO. First of all you should read [here](http://stackoverflow.com/help/how-to-ask) about how to ask a good question; a good question has better changes to be solved and you to receive help. On the other hand a read of [this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) is also good. It explains how to create a reproducible example in R. Help users to help you by providing a piece of your data a desired output and things you have tried so far. – SabDeM Sep 15 '15 at 20:08

1 Answers1

1

I suggest using ifelse function:

mydata2$Partner.Type <- ifelse(  mydata2$Destination.DisplayName == mydata3$If,
                                mydata3$Then,
                                mydata2$Partner.Type)

EDIT

If columns have not have the same lengths then try sapply

sapply(mydata2$Destination.DisplayName, function(element){
   if ( element %in% mydata3$If ){
   return(mydata3$Then[which(element == mydata3$If)])
} else {
return(mydata2$Partner.Type[which(element == mydata2$Destination.DisplayName)])
}
}) -> mydata2$Destination.DisplayName

EDIT2

Or you can use dplyr package and left_join function.

library(dplyr)
mydata2 %>%
   left_join(mydata3, 
              by = c("Destination.DisplayName" = "If")
   ) -> joined_mydatas

ifelse(is.na(joined_mydatas$Then),
        joined_mydatas$Partner.Type,
        joined_mydatas$Then) -> mydata2$Partner.Type
Marcin Kosiński
  • 7,578
  • 5
  • 49
  • 95