如何在R的XTS中提取月的最后第n个交易日?

如何在R的XTS中提取月的最后第n个交易日?,r,subset,xts,R,Subset,Xts,这个问题与此密切相关,我从中得到了一个很好的答案: library(xts) data(sample_matrix) x <- as.xts(sample_matrix) do.call(rbind, lapply(split(x, "months"), function(x) x[10])) # Open High Low Close # 2007-01-11 49.88529 50.23910 49.88529 50.23910 #

这个问题与此密切相关,我从中得到了一个很好的答案:

library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)
do.call(rbind, lapply(split(x, "months"), function(x) x[10]))
#                Open     High      Low    Close
# 2007-01-11 49.88529 50.23910 49.88529 50.23910
# 2007-02-10 50.68923 50.72696 50.60707 50.69562
# 2007-03-10 49.79370 49.88984 49.70385 49.88698
# 2007-04-10 49.55704 49.78776 49.55704 49.76984
# 2007-05-10 48.83479 48.84549 48.38001 48.38001
# 2007-06-10 47.74899 47.74899 47.28685 47.28685
我想有一个函数,提取每个月的最后一个交易日,并形成一个新的数据框架。例如,如果我想提取每个月的最后一个交易日。输出应该如下表所示

      date change   open   high    low  close    volume
1990-01-30 -0.683 325.20 325.73 319.83 322.98 186030000
1990-02-27  0.484 328.68 331.94 328.47 330.26 152590000
1990-03-29 -0.354 342.00 342.07 339.77 340.79 132190000
1990-04-27 -1.144 332.92 333.57 328.71 329.11 130630000

请注意,我想提取每个月的最后第n个数据点,而不是最后第n个日历日期。您可以使用
tail

n <- 2
do.call(rbind, lapply(split(x, "months"), function(x) tail(x, n)))

#                Open     High      Low    Close
# 2007-01-30 49.85477 50.02180 49.77242 50.02180
# 2007-01-31 50.07049 50.22578 50.07049 50.22578
# 2007-02-27 50.74333 50.78909 50.61874 50.69206
# 2007-02-28 50.69435 50.77091 50.59881 50.77091
# 2007-03-30 48.74562 49.00218 48.74562 48.93546
# 2007-03-31 48.95616 49.09728 48.95616 48.97490
# 2007-04-29 49.30289 49.30289 49.05676 49.13529
# 2007-04-30 49.13825 49.33974 49.11500 49.33974
# 2007-05-30 47.78866 47.93267 47.78866 47.83291
# 2007-05-31 47.82845 47.84044 47.73780 47.73780
# 2007-06-29 47.63629 47.77563 47.61733 47.66471
# 2007-06-30 47.67468 47.94127 47.67468 47.76719

n这不是预期的输出吗?
n <- 2
do.call(rbind, lapply(split(x, "months"), function(x) tail(x, n)))

#                Open     High      Low    Close
# 2007-01-30 49.85477 50.02180 49.77242 50.02180
# 2007-01-31 50.07049 50.22578 50.07049 50.22578
# 2007-02-27 50.74333 50.78909 50.61874 50.69206
# 2007-02-28 50.69435 50.77091 50.59881 50.77091
# 2007-03-30 48.74562 49.00218 48.74562 48.93546
# 2007-03-31 48.95616 49.09728 48.95616 48.97490
# 2007-04-29 49.30289 49.30289 49.05676 49.13529
# 2007-04-30 49.13825 49.33974 49.11500 49.33974
# 2007-05-30 47.78866 47.93267 47.78866 47.83291
# 2007-05-31 47.82845 47.84044 47.73780 47.73780
# 2007-06-29 47.63629 47.77563 47.61733 47.66471
# 2007-06-30 47.67468 47.94127 47.67468 47.76719
library(xts)
data(sample_matrix)
x <- as.xts(sample_matrix)