Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/jpa/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在r中从一个数据帧提取数据到另一个数据帧_R_Finance - Fatal编程技术网

在r中从一个数据帧提取数据到另一个数据帧

在r中从一个数据帧提取数据到另一个数据帧,r,finance,R,Finance,我有一个数据框架,包含了几年来证券交易所的每日价格及其各自的日期。我想为每个月提取一个月的最后3个观察值和下个月的前5个观察值,并将其存储在新的数据框中 除了日期(格式为“%Y-%m-%d”)之外,我还有一个列,每个月的每个交易日都有一个计数器。示例数据如下所示: df$date <- as.Date(c("2017-03-25","2017-03-26","2017-03-27","2017-03-29&quo

我有一个数据框架,包含了几年来证券交易所的每日价格及其各自的日期。我想为每个月提取一个月的最后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)
df$date第一个想法:

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)
date又快又脏:
添加一列类似于DayofMonth列,但向下移动了3

df$dom2 <- df$DayofMonth[4:(nrow(df)+3)]
subset(df, DayofMonth<=5 | dom2<=3)

df$dom2,如您所见,它包含您第一个问题的代码。我希望这有帮助:)再次非常感谢@peter!非常有用:)我发布了另一个问题,关于如何使用
df$DayofMonth
在原始数据帧(df)中创建一个虚拟变量,对于下个月的最后3次和前5次观察值为1,否则为0,如果您想看一看的话!