2

コードは次のとおりです。編集:以下の再現可能なコードを参照してください

>require("quantmod")   
>
> corn <- as.xts(read.zoo("~/CORN.csv", sep=",", format ="%m/%d/%Y", header=TRUE))
> 
> head(corn)
           [,1]
1962-01-03 4.03
1962-01-04 3.99
1962-01-05 4.02
1962-01-08 4.03
1962-01-09 4.05
1962-01-10 4.07
> 
> corn <- to.weekly(corn)[,4]
> 
> head(corn)
           corn.Close
1962-01-05       4.02
1962-01-12       4.08
1962-01-19       4.11
1962-01-26       4.11
1962-02-02       4.08
1962-02-09       4.05

毎週火曜日にどのように始まりますか? の線に沿った何か

indexAt='startof("Tuesday")'

ここで、indexAt は to.weekly() 関数のパラメーター変数です。

これの目的は、毎週の COT データと一致させることです。

編集 ##################

再現可能なコードを提供しないことで混乱を招いたため、以下に J. Winchester の提案に基づいて部分的な解決策を組み込んだものをいくつか示します。

> getSymbols("GLD")
[1] "GLD"
> GLD <- GLD[,4]
> head(GLD, n=2)
           GLD.Close
2007-01-03     62.28
2007-01-04     61.65
> tues <- weekdays(time(GLD)) == "Tuesday"
> gold <- merge(GLD, tues)
> head(gold, n=5)
           GLD.Close tues
2007-01-03     62.28    0
2007-01-04     61.65    0
2007-01-05     60.17    0
2007-01-08     60.48    0
2007-01-09     60.85    1
4

2 に答える 2

3

これはどうでしょうか (Alaacano のダミー データ フレームに基づく)。

corn$tuesdays <- weekdays(corn$dates) == "Tuesday"

# count days from any partial week at the beginning
start_len <- ifelse(corn$tuesdays[1], 0, rle(corn$tuesdays)$lengths[1])

# assign a week value to every row
corn$week <- c(rep(0, start_len), 1 + seq_len(nrow(corn) - start_len) %/% 7)

# concatenate the start date of the first (possibly incomplete) week
# to the start dates for all the following weeks
week_starts <- as.Date(corn$dates[corn$tuesdays])
if(start_len > 0) week_starts <- c(week_starts[1] - 7, week_starts) 

# calculate weekly means and assemble to a data frame
corn_values <- aggregate(value~week, data = corn, FUN = mean)$value
corn_weekly <- data.frame(week_starts, corn_values)
于 2011-03-28T23:18:59.007 に答える
0

よりエレガントな解決策があるかもしれませんが、これはトリックを行う必要があります

# generate some fake data for 2011
corn <- data.frame(dates=as.Date("2011-01-01") + seq(0,365), value=runif(366))

# get the day of week
corn$dow <- chron::day.of.week(as.numeric(strftime(corn$dates, "%Y")),
                               as.numeric(strftime(corn$dates, "%m")),
                               as.numeric(strftime(corn$dates, "%d")))
# take subset     
corn <- subset(corn, dow==2)

出力は次のようになります。

> head(corn)
        dates      value dow
11 2011-01-11 0.54688767   2
17 2011-01-17 0.22249506   2
22 2011-01-22 0.61725913   2
28 2011-01-28 0.45681763   2
36 2011-02-05 0.77839486   2
41 2011-02-10 0.07201445   2

曜日を削除したり、corn$datesの代わりにrow.namesを使用したりできます

于 2011-03-28T20:41:43.563 に答える