如何解决在R中将数据从一个数据帧提取到另一个
我有一个数据框,其中包含几年的证券交易所每日价格以及它们各自的日期。我想每个月提取一个月中的最后3个观察值和下个月的前5个观察值,并将其存储在新的数据框中。
除了日期(格式为“%Y-%m-%d”)之外,我还有一个列,每个月的交易日都有一个计数器。示例数据如下:
df$date <- as.Date(c("2017-03-25","2017-03-26","2017-03-27","2017-03-29","2017-03-30","2017-03-31","2017-04-03","2017-04-04","2017-04-05","2017-04-06","2017-04-07","2017-04-08","2017-04-09"))
df$DayofMonth <- c(18,19,20,21,22,23,1,2,3,4,5,6,7)
df$price <- (100,100.53,101.3,100.94,101.42,101.40,101.85,102,101.9,102.31,102.1,102.23)
现在我要提取3月的最后3个观测值和4月的前5个观测值(然后是4月的最后3个观测值和5月的前5个观测值,包括相应行的所有列),然后将其存储在一个新的数据框中。唯一的问题是我该怎么做?
感谢您的帮助!
解决方法
第一个想法:
date <- c("2017-03-25","2017-03-26","2017-03-27","2017-03-29","2017-03-30","2017-03-31","2017-04-03","2017-04-04","2017-04-05","2017-04-06","2017-04-07","2017-04-08","2017-04-09")
df <- data.table(Date = date)
df[,YearMonth:=str_sub(Date,1,7)]
df[,DayofMonth := seq(.N),by = YearMonth]
first <- df[,.SD[1:ifelse(.N < 5,.N,5)],by = YearMonth] #first trading days each month
last <- df[,.SD[(ifelse((.N-2) < 0,(.N-2))):.N],by = YearMonth] #last trading days each month
final <- rbind(first,last)
setorder(final,Date)
# be aware that it leads to duplicates for a month if it has less than 8 trading days,# to resolve that use unique()
final <- unique(final)
,
快速又脏: 添加类似于DayofMonth列的列,但向下移动3列
df$dom2 <- df$DayofMonth[4:(nrow(df)+3)]
subset(df,DayofMonth<=5 | dom2<=3)
我们仍然使用实际的DayofMonth列进行过滤的唯一原因(而不是jsut说dom2
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。