我想使用for-loop對單個行的元素進行計算。 我有兩個data.frames使用列表在R中存儲雙循環(for-loop)的結果
- DF:包含所有交易日的股票
- 事件的數據:包含的股票
的唯一事件天的數據雖然有可能是一個更容易這個具體例子的方法,我想知道如何做一個循環循環(for循環)這樣的任務。
首先,我data.frames:
comp1 <- c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3)
date1 <- c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
ret <- c(1.2,2.2,-0.5,0.98,0.73,-1.3,-0.02,0.3,1.1,2.0,1.9,-0.98,1.45,1.71,0.03)
df <- data.frame(comp1,date1,ret)
comp2 <- c(1,1,2,2,2,3,3)
date2 <- c(2,4,1,2,5,4,5)
q <- paste("")
events <- data.frame(comp2,date2,q)
df
# comp1 date1 ret
# 1 1 1 1.20
# 2 1 2 2.20
# 3 1 3 -0.50
# 4 1 4 0.98
# 5 1 5 0.73
# 6 2 1 -1.30
# 7 2 2 -0.02
# 8 2 3 0.30
# 9 2 4 1.10
# 10 2 5 2.00
# 11 3 1 1.90
# 12 3 2 -0.98
# 13 3 3 1.45
# 14 3 4 1.71
# 15 3 5 0.03
events
# comp2 date2 q
# 1 1 2
# 2 1 4
# 3 2 1
# 4 2 2
# 5 2 5
# 6 3 4
# 7 3 5
我要讓DF $ RET的計算。作爲一個例子,我們只需要2 * df $ ret。每個活動日的結果應存儲在mylist中。最終輸出應該是data.frame「events」,其中列「q」表示要存儲計算結果。
# important objects:
companies <- as.vector(unique(df$comp1)) # all the companies (here: 1, 2, 3)
days <- as.vector(unique(df$date1)) # all the trading-days (here: 1, 2, 3, 4, 5)
mylist <- vector('list', length(companies)) # a list where the results should be stored for each company
我想出了一些代碼段不工作。但我仍然認爲它應該是這個樣子:
for(i in 1:nrow(events)) {
events_k <- events[which(comp1==companies[i]),] # data of all event days of company i
df_k <- df[which(comp2==companies[i]),] # data of all trading days of company i
for(j in 1:nrow(df_k)) {
events_k[j, "q"] <- df_k[which(days==events_k[j,"date2"]), "ret"] * 2
}
mylist[i] <- events_k
}
我不明白如何設置其他的循環,以及如何結果存儲在裏面MYLIST循環。任何幫助讚賞!
謝謝!
感謝您的回答!對於第一家公司的第一次進入,您的方法起作用,但不適用於其他活動!這是爲什麼? – cptn