简体   繁体   中英

Conditional Statement in R (indicator) based off matching values to another dataset

I have two datasets

dataset1 with column fruit, customer_num

dataset2 with column fruit2, customer_num

So lets say I do a left join with dataset 1 to dataset 2, using customer_num as the joiner. Now I got a dataset with fruit and fruit2 as column variables.

How can a create an indicator to say if fruit==fruit2 then 1 else 0 ?

ifelse would be easiest, assuming it is in the same dataframe. Example using the dplyr package

    dataset1 %>%
    mutate(Match=ifelse(fruit==fruit2,1,0))

This will create a column called Match and do 1 if they match, 0 if they do not

You could do it like this (my example):

# I've created example of customer_num where I presumed that this are numbers
fruit <- data.frame(customer_num = c(1, 2, 3, 4, 5, 6))
fruit2 <- data.frame(customer_num = c(1, 2, 3, 10, 11, 12))

# Vector in data frame
df <- data.frame(fruit, fruit2)

# And match values / Indicator
dat<-within(df,match <- ifelse (fruit == fruit2,1,0))

# Output
  customer_num customer_num.1 customer_num
1            1              1            1
2            2              2            1
3            3              3            1
4            4             10            0
5            5             11            0
6            6             12            0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM