【发布时间】:2016-07-29 13:58:11
【问题描述】:
这是我的第一篇文章,所以如果我不够具体,我深表歉意。
我有一个月份序列和一个包含大约 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 序列中的每条记录,都会计算从每个唯一标识符的启动月份到该记录(月份日期)的月数。但是,这一直在踢回错误:
Months.2 中的错误 - i : 二元运算符的非数字参数
我不确定解决方案是什么,或者我是否为此正确使用了 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
【问题讨论】:
-
您能否发布一个您期望的输出示例,以便人们更容易正确回答您的问题?
-
我添加了预期的输出,对此感到抱歉!