我有一个数据框,其中包含日期列和一些其他值列.我想从数据框中提取日期列与预先存在的日期列表中的任何元素匹配的行.例如,使用一个元素的列表,日期"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)
Run Code Online (Sandbox Code Playgroud)
...生成此数据框:
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
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
testdf[which(testdf$col3 %in% c('25','29')),]
Run Code Online (Sandbox Code Playgroud)
产生这个:
mydate col1 col2 col3
5 2012-01-05 5 15 25
9 2012-01-09 9 19 29
Run Code Online (Sandbox Code Playgroud)
我可以将其推广到这样的列表:
myvalues <- c('25','29')
testdf[which(testdf$col3 %in% myvalues),]
Run Code Online (Sandbox Code Playgroud)
我得到相同的输出.所以我原本以为我能用相同的方法来约会,但看来我错了.这样做:
testdf[which(testdf$mydate %in% c('2012-01-05','2012-01-09')),]
Run Code Online (Sandbox Code Playgroud)
得到我这个:
[1] mydate col1 col2 col3
<0 rows> (or 0-length row.names)
Run Code Online (Sandbox Code Playgroud)
在他们自己的列表中弹出日期 - 这是最终目标 - 也无济于事.我可以通过循环或应用函数来思考这个方法,但在我看来,对于可能是相当常见的要求,必须有一种更简单的方法.是不是我再次忽视了一些简单的事情?
问:如何对具有日期列的数据框的那些行进行子集,其中日期列的值与日期列表中的一个匹配?
Ryo*_*ogi 24
您必须使用(在控制台上尝试)将日期string转换为Date变量.额外奖励:你可以放弃哪个:as.Date?as.Date
> testdf[testdf$mydate %in% as.Date(c('2012-01-05', '2012-01-09')),]
mydate col1 col2 col3
5 2012-01-05 5 15 25
9 2012-01-09 9 19 29
Run Code Online (Sandbox Code Playgroud)
A5C*_*2T1 11
到目前为止,这两个建议都绝对是好的,但是如果你要做很多关于日期的工作,你可能想要花一些时间来使用这个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
Run Code Online (Sandbox Code Playgroud)
您还可以从另一个向量中获取日期.
# 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
Run Code Online (Sandbox Code Playgroud)
该xts软件包将为您提供智能的子集选项.例如,testdfx["2012-03"]将返回三月份的所有数据; testdfx["2012"]将返回一年; testdfx["/2012-02-15"]将数据从数据集的开头返回到2月15日; 并将testdfx["2012-02-15/"]从2月15日到数据集的末尾.