R:匹配具有最小时间间隔的两个数据帧的行

时间:2016-12-24 12:30:00

标签: r time match

给定两个数据帧,对于第一个数据帧中的每一行,找到具有相同product_id的行,但visiting_time更大,并且两行之间的时间间隔为最小。

例如

第2行cart_add_data与purchase_data的第一行匹配。

BTW,计算效率也很重要。

数据框: cart_add_data

    visting_time           product_id
 1  2012-01-08 13:29:39    878435
 2  2012-01-08 13:36:52    122100
 3  2012-01-08 13:38:47    150473
 4  2012-01-14 21:06:36    169403
 5  2012-01-14 21:06:36    137092

数据框: purchase_data

    visting_time            product_id
 1  2012-01-08 13:42:35     122100 
 2  2012-01-08 13:42:35     138857 
 3  2012-01-08 13:42:35     150473 
 4  2012-01-18 22:15:04     140376 
 5  2012-02-02 09:21:28     130437

1 个答案:

答案 0 :(得分:0)

我认为这可以做你想要的(?)(我添加了几行以符合你的其他标准:

using System.Collections.Generic;
using System.Web.Mvc;
using System.Data.SqlClient;

namespace StockHoldings.Controllers
{
    public class ReportsController : Controller
    {

        // GET: Reports/ClientInvestmentsSince
        public ActionResult ClientInvestmentsSince()
        {
            string str = @"Data Source=USER\SQLEXPRESS;Initial Catalog=HoldingsConnectionString2;Integrated Security=True";
            SqlConnection con = new SqlConnection(str);
            string query = "select ID, LastName from Clients";
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            List<SelectListItem> li = new List<SelectListItem>();
            while (rdr.Read())
            {
                li.Add(new SelectListItem { Text = rdr[1].ToString(), Value = rdr[0].ToString() });
            }
            ViewData["client"] = li;

            return View();
        }


        public JsonResult ClientInvestmentsSince2(int Id)
        {
            string str = @"Data Source=USER\SQLEXPRESS;Initial Catalog=HoldingsConnectionString2;Integrated Security=True";
            SqlConnection con = new SqlConnection(str);
            string query = "select ID, Fund from Investments where Client_ID = " + Id;
            SqlCommand cmd = new SqlCommand(query, con);
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            List<SelectListItem> li = new List<SelectListItem>();
            while (rdr.Read())
            {
                li.Add(new SelectListItem { Text = rdr["ID"].ToString(), Value = rdr["Fund"].ToString() });
            }
            ViewData["Fund"] = li;

*********************************************

// ViewData["Fund"] is loading correctly, and there is a clean exit of the method.


            return Json(li, JsonRequestBehavior.AllowGet);
        }

}
}