[英]Extracting data from one dataframe to another in 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, 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, 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 列(而不是說 dom2<=8)進行過濾的唯一原因是,在 dom2 的末尾將有一個 NA 用於您的示例。 不知道您的真實數據如何,但安全總比抱歉好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.