我有一个带有日期列和其他一些值列的数据框。我想从数据框中提取日期列与预先存在的日期列表中的任何元素匹配的行。例如,使用一个元素的列表,日期“2012-01-01”将从数据框中提取日期为“2012-01-01”的行。
对于数字,我想我知道如何匹配这些值。这段代码:
testdf <- data.frame(mydate = seq(as.Date('2012-01-01'),
as.Date('2012-01-10'), by = 'day'),
col1 = 1:10,
col2 = 11:20,
col3 = 21:30)
...生成此数据框:
mydate col1 col2 col3
1 2012-01-01 1 11 21
2 2012-01-02 2 12 22
3 2012-01-03 3 13 23
4 2012-01-04 4 14 24
5 2012-01-05 5 15 25
6 2012-01-06 6 16 26
7 2012-01-07 7 17 27
8 2012-01-08 8 18 28
9 2012-01-09 9 19 29
10 2012-01-10 10 20 30
我可以做这个:
testdf[which(testdf$col3 %in% c('25','29')),]
输出这个:
mydate col1 col2 col3
5 2012-01-05 5 15 25
9 2012-01-09 9 19 29
我可以将其推广到这样的列表:
myvalues <- c('25','29')
testdf[which(testdf$col3 %in% myvalues),]
我得到相同的输出。所以我原本以为我可以使用相同的方法来约会,但看起来我错了。这样做:
testdf[which(testdf$mydate %in% c('2012-01-05','2012-01-09')),]
得到我这个:
[1] mydate col1 col2 col3
<0 rows> (or 0-length row.names)
在他们自己的列表中弹出日期 - 这是最终目标 - 也无济于事。我可以通过循环或应用函数来思考这个方法。但在我看来,肯定有一种更简单的方法。是不是我遗漏了一些简单的东西?
问:如何对具有日期列的数据框的那些行进行子集,这些日期列的值与日期列表中的一个匹配?
发布于 2018-12-19 15:52:03
到目前为止这两个建议肯定都很好,但是如果你要做很多关于日期的工作,你可能想要花一些时间来使用这个xts
包:
# Some sample data for 90 consecutive days
set.seed(1)
testdf <- data.frame(mydate = seq(as.Date('2012-01-01'),
length.out=90, by = 'day'),
col1 = rnorm(90), col2 = rnorm(90),
col3 = rnorm(90))
# Convert the data to an xts object
require(xts)
testdfx = xts(testdf, order.by=testdf$mydate)
# Take a random sample of dates
testdfx[sample(index(testdfx), 5)]
# col1 col2 col3
# 2012-01-17 -0.01619026 0.71670748 1.44115771
# 2012-01-29 -0.47815006 0.49418833 -0.01339952
# 2012-02-05 -0.41499456 0.71266631 1.51974503
# 2012-02-27 -1.04413463 0.01739562 -1.18645864
# 2012-03-26 0.33295037 -0.03472603 0.27005490
# Get specific dates
testdfx[c('2012-01-05', '2012-01-09')]
# col1 col2 col3
# 2012-01-05 0.3295078 1.586833 0.5210227
# 2012-01-09 0.5757814 -1.224613 -0.4302118
您还可以从另一个向量中获取日期。
# Get dates from another vector
lookup = c("2012-01-12", "2012-01-31", "2012-03-05", "2012-03-19")
testdfx[lookup]
testdfx[lookup]
# col1 col2 col3
# 2012-01-12 0.38984324 0.04211587 0.4020118
# 2012-01-31 1.35867955 -0.50595746 -0.1643758
# 2012-03-05 -0.74327321 -1.48746031 1.1629646
# 2012-03-19 0.07434132 -0.14439960 0.3747244
该xts
软件包将为您提供智能的子集选项。例如,testdfx["2012-03"]
将返回三月份的所有数据; testdfx["2012"]
将返回一年; testdfx["/2012-02-15"]
将数据从数据集的开头返回到2月15日; testdfx["2012-02-15/"]
从2月15日到数据集的末尾。
https://stackoverflow.com/questions/-100006333
复制相似问题