例如,我有变量
Store.Number <- c("105, 105, 105, 106, 106, 106, 110, 110, 110, 110")
Date <- c("2017-01-04", "2016-07-06", "2016-04-04", "2017-01-31", "2016-10-31",
"2016-05-11", "2017-01-26", "2016-10-28", "2016-07-20", "2016-04-27")
Jan012016 <- c("369",NA,NA.......)
a <- as.Date("01/01/2016", "%m/%d/%Y)
我想编写一个函数,使第一个循环检查
for i=1
Store.Number[i+1,1] = Store.Number [i,1]
If "True"
abs(Date[i,2] - Date[i+1,2])
Else
abs(Date[i,2] - a)
示例:
Store.Number[2,1] = Store.Number [1,1] > TRUE
Jan012016 = abs(Date[2,2] - Date[1,2])
Else
Jan012016 = abs(Date[i,2] - a)
答案 0 :(得分:0)
R中最常用于将数据拆分为子集并执行计算的函数可能是tapply
和aggregate
。在这种情况下,tapply
给出的输出最接近您想要的输出,例如:
Store.Number <- c(105, 105, 105, 106, 106, 106, 110, 110, 110, 110)
Date <- as.Date(c("2017-01-04", "2016-07-06", "2016-04-04", "2017-01-31", "2016-10-31",
"2016-05-11", "2017-01-26", "2016-10-28", "2016-07-20", "2016-04-27"), "%Y-%m-%d")
a <- as.Date("01/01/2016", "%m/%d/%Y")
store.diffs <- tapply(Date, Store.Number, function(x)abs(diff(c(a,x))))
Jan012016 <- do.call(c,store.diffs)
names(Jan012016) <- NULL
Jan012016
# Time differences in days
# [1] 369 182 93 396 92 173 391 90 100 84
请注意,我已删除了Store.Number
定义中的引号,并将Date
从字符转换为日期。