這是我的第一篇文章,所以如果我沒有足夠具體,我會道歉。計算從一個數據框中的列到按照多個行的順序中的每個月的月數
我有一個月的序列和一個約100行的數據框,每個都有一個唯一的標識符。每個標識符都與啓動日期相關聯。我正在計算序列中每月每個唯一標識符啓動後的月數。我已經嘗試寫一個for循環來完成這個。
下例:
# Build Example Data Frame #
x_example <- c("A","B","C","D","E")
y_example <- c("2013-10","2013-10","2014-04","2015-06","2014-01")
x_name <- "ID"
y_name <- "StartUp"
df_example <- data.frame(x_example,y_example)
names(df_example) <- c(x_name,y_name)
# Create Sequence of Months, Format to match Data Frame, Reverse for the For Loop #
base.date <- as.Date(c("2015-11-1"))
Months <- seq.Date(from = base.date , to = Sys.Date(), by = "month")
Months.1 <- format(Months, "%Y-%m")
Months.2 <- rev(Months.1)
# Create For Loop #
require(zoo)
for(i in seq_along(Months.2))
{
for(j in 1:length(summary(as.factor(df_example$ID), maxsum = 100000)))
{
Active.Months <- 12 * as.numeric((as.yearmon(Months.2 - i) - as.yearmon(df_example$StartUp)))
}
}
背後的for循環是在Months.2序列中的每個記錄,會有的月數的計算,以該記錄(年月日)從想法每個唯一標識符的啓動月份。然而,這已被踢回錯誤:
Error in Months.2 - i : non-numeric argument to binary operator
我不知道該解決方案是什麼,或者,如果我使用的for循環正常了這一點。
在此先感謝您解決此問題的任何幫助!
編輯:這是我希望我的預期的結果將是(這僅僅是一個樣品有序列中個月以上):
ID Start Up Month 2015-11 2015-12 2015-12 2016-02 2016-03
1 A 2013-10 25 26 27 28 29
2 B 2013-10 25 26 27 28 29
3 C 2014-04 19 20 21 22 23
4 D 2015-06 5 6 7 8 9
5 E 2014-01 22 23 24 25 26
你能發表一個你期待什麼輸出的例子,以便人們更容易正確回答你的問題嗎? –
我加了預期的輸出,對不起! – DW1