按多个条件匹配和替换数据框的列

时间:2016-08-29 19:00:17

标签: r datetime dataframe dplyr

干杯, 我有两个具有以下结构的数据框。

DF1:
Airlines           HeadQ      Date           Cost_Index
American           PHX        07-31-2016     220
American           ATL        08-31-2016     150
American           ATL        10-31-2016     150
Delta              ATL        10-31-2016     180
American           ATL        08-31-2017     200

第二数据帧DF2具有以下结构:

DF2:
Airlines           HeadQ      Date          
American           ATL        09-30-2016
Delta              ATL        03-31-2017

现在查看数据帧DF1和DF2,我想将DF1改为以下数据帧。

DF1:
Airlines           HeadQ      Date           Cost_Index
American           PHX        07-31-2016     220
American           ATL        08-31-2016     0
American           ATL        10-31-2016     150
Delta              ATL        10-31-2016     180
American           ATL        08-31-2017     200

条件是,从DF2查找航空公司和DF1的HeadQ,以及DF1 $ Date< DF2 $ Date然后将Cost_Index设为0,否则继续使用Cost_Index。

我尝试了,但没有成功:

DF1$Cost_Index <- ifelse(DF1$Airlines == DF2$Airlines & DF1$HeadQ == DF2$HeadQ 
        & DF1$Date < DF2$Date, 0, DF1$Cost_Index)


Warning:
1: In DF1$Airlines == DF2$Airlines : longer object
length is not a multiple of shorter object length". 
2: In<=.default(DF1$Date, DF2$Date) : longer object length is not a
multiple of shorter object length

DF1:
Airlines           HeadQ      Date           Cost_Index
American           PHX        07-31-2016     220
American           ATL        08-31-2016     0
American           ATL        10-31-2016     0
Delta              ATL        10-31-2016     0
American           ATL        08-31-2017     200

有人能指出我正确的方向吗?

注意:

str(DF1$Date): Date, format: "2016-10-31"
str(DF2$Date): Date, format: "2016-08-31"

1 个答案:

答案 0 :(得分:14)

使用条件联接功能(自use strict; use warnings; use DBI; print "HTTP/1.0 200 OK\n"; print "Content-Type: text/html\n\n\n"; my $dbh=DBI->connect("DBI:mysql:database=address_book;host=**.**.***.159", "***", "****"); my $o = new CGI; my $Contact_ID = $o -> param("Contact_ID"); my $First_Name = $o -> param("First_Name"); my $Last_Name = $o -> param("Last_Name"); my $Address = $o -> param("Address"); my $Phone = $o -> param("Phone"); my $Birthday = $o -> param("Birthday"); my $Email = $o -> param("Email"); my $Relationship = $o -> param("Relationship"); $dbh->do("INSERT INTO Contacts VALUES (?, ?, ?, ?, ?, ?, ?, ?)", undef, '0', $First_Name, $Last_Name, $Address, $Phone, $Birthday, $Email, $Relationship); $dbh->disconnect(); 起),我按照以下方式执行此操作:

1.9.8