合并2个日期数据集

时间:2016-10-11 22:46:43

标签: r date type-conversion posixct posixlt

可重复使用的代码

#include <vector>

#define BOOST_ERROR_CODE_HEADER_ONLY 1
#include <boost/asio.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

std::vector<int> sample_a_chunk(unsigned int rate, unsigned int block_size_in_seconds) {
  std::vector<int> data;
  const unsigned int times = rate * block_size_in_seconds;
  auto expiration_time = boost::posix_time::microsec_clock::local_time();
  const auto delay = boost::posix_time::microseconds(1000000/rate);
  boost::asio::io_service io;
  boost::asio::deadline_timer t(io);

  for (unsigned int j=0; j < times; j++) {
    expiration_time += delay;
    data.emplace_back(/* read the value from the gpio */);
    t.expires_at(expiration_time);
    t.wait();
  }
  return data;
}

基本上,我有两个我想要相乘的日期,所以我会看到相交的日期。

您可以在此要点中找到代码 https://gist.github.com/baditaflorin/46b35b3044f69ed329e4c44067b7b246

现在tclass是日期,我使用

从csv文件导入了数据
library("zoo")  
library("xts")
x <- structure(c("2012-09-27 09:08:37", "2012-09-29 10:06:33", "2012-10-01 09:44:36","2012-10-04 14:37:05", "2012-10-15 13:18:21", "2012-10-17 17:33:46","2012-10-18 11:52:13", "2016-10-06 15:11:01", "2016-10-07 13:00:09","2016-10-07 12:20:57"), class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", format = "%Y-%m-%d %H:%M:%S", index = structure(c(1348704000,1348876800, 1349049600, 1349308800, 1350259200, 1350432000, 1350518400,1475712000, 1475798400, 1475798400), tzone = "UTC", tclass = "Date"), .Dim = c(10L,1L)) 
y <- structure(c("1961-08-04 10:00:00", "1971-01-01 11:00:00", "1978-01-01 11:00:00","1979-01-01 11:00:00", "1983-01-01 11:00:00", "1984-01-01 11:00:00","1985-01-01 11:00:00", "2016-10-07 20:28:24", "2016-10-07 18:27:54","2016-10-08 00:38:40"), class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date", .indexTZ = "UTC", tzone = "UTC", format = "%Y-%m-%d %H:%M:%S", index = structure(c(-265420800,31536000, 252460800, 283996800, 410227200, 441763200, 473385600,1475798400, 1475798400, 1475884800), tzone = "UTC", tclass = "Date"), .Dim = c(10L,1L)) 
x+y
#expected result
#  get results
#what happens
#Error in `+.default`(x, y) : non-numeric argument to binary operator

我也尝试转换数据但出错了

x <- xts(csv_file, format = "%Y-%m-%d %H:%M:%S",order.by=as.Date(csv_file))

这些是我的会话信息:

x2 <- as.Date.POSIXlt( x , format = "%Y-%m-%d %H:%M:%S" , tz = "GMT") 

Error in as.POSIXlt.default(x, tz, ...) : 
  do not know how to convert 'x' to class “POSIXlt” 

1 个答案:

答案 0 :(得分:2)

根据您的评论,您需要两个xts对象的索引列上的交集或内部联接。

> intersect( index(x), index(y) )
[1] 17081
> as.Date( intersect( index(x), index(y) ) )
[1] "2016-10-07"

xts中的合并默认为&#34;外部&#34;这与基础R合并功能不同,因此添加&#34; join&#34;规范是必要的:

> merge(x,y, join="inner")
           x                     y                    
2016-10-07 "2016-10-07 13:00:09" "2016-10-07 20:28:24"
2016-10-07 "2016-10-07 12:20:57" "2016-10-07 18:27:54"
相关问题