繁体   English   中英

R(指标)中的条件语句基于与另一个数据集的匹配值

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

我有两个数据集

具有列结果为customer_num的数据集1

具有水果2列,customer_num的数据集2

因此,可以说我使用customer_num作为联接器,对数据集1进行左联接到数据集2。 现在,我得到了一个数据集,其中有fruit和fruit2作为列变量。

如何创建一个指标来说明是否fruit == fruit2然后1 else 0?

假设它位于同一数据帧中,则ifelse最简单。 使用dplyr包的示例

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

这将创建一个名为Match的列,如果匹配则执行1,如果不匹配则执行0

您可以这样做(我的例子):

# 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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