根据具体日期和计数在列中添加1

时间:2016-05-31 10:54:08

标签: r date count

我有一个表,包括每日值(值)的时间序列,日期和一个“0”的列。以下是变量:

value <- c(37,19.75,19.5,14.5,24.75,25,25.5,19.75,19.75,14.25,21.25,21.75,17.5,16.25,14.5,
           14.5,14.75,9.5,11.75,15.25,14.25,16.5,13.5,18.25,13.5,11.25,10.75,12,8.5,
           9.75,14.75)
Date <- c("1997-05-01","1997-05-02","1997-05-03","1997-05-04","1997-05-05",
          "1997-05-06","1997-05-07","1997-05-08","1997-05-09","1997-05-10",
          "1997-05-11","1997-05-12","1997-05-13","1997-05-14","1997-05-15",
          "1997-05-16","1997-05-17","1997-05-18","1997-05-19","1997-05-20",
          "1997-05-21","1997-05-22","1997-05-23","1997-05-24","1997-05-25",
          "1997-05-26","1997-05-27","1997-05-28","1997-05-29","1997-05-30",
          "1997-05-31")
ncol <- c(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)`

data <- data.frame(value, Date, ncol)

使用“as.Date”功能将日期格式化为日期。现在我想在特定的5天内将“1”添加到“newcol”(0s)列中的某些值,例如。在时间序列中的“1997.05.05”,“1997.05.11”,“1997.05.14”,“1997.05.18”,“1997.05.25”。

我创建了这个函数,但仅适用于日期:

x <- 1
i <- which(format(data$Date, "%Y.%m.%d") == "1997.05.05") 
data$newcol[i] <- data$newcol[i] + x

如何做到最好?

然后我想计算前5天特定日期(newcol = 1)的“值”出现&gt; 20的次数。例如,日期1997.05.25值出现的次数&gt; 20到1997.05.21。

2 个答案:

答案 0 :(得分:0)

这回答了你问题的第一部分:

library(data.table)


setDT(data)[ Date %in% c("1997-05-05","1997-05-11","1997-05-14","1997-05-18","1997-05-25"), newcol := ncol+1 ]

# or perhaps better:

setDT(data)[, newcol := ifelse(Date %in% c("1997-05-05","1997-05-11","1997-05-14","1997-05-18","1997-05-25"), ncol+1, 0) ]

答案 1 :(得分:0)

使用base R可以完成此操作

transform(data, newcol = as.integer(as.character(Date) %in% 
     c("1997-05-05","1997-05-11","1997-05-14","1997-05-18","1997-05-25")))