将数据帧中一定范围的值与数字相乘

时间:2019-06-19 09:58:52

标签: r time-series

我有以下数据框:

Date<-c("2013-01-01 02:00:00","2013-01-02 02:00:00","2013-01-03 02:00:00","2013-01-01 02:00:00","2013-01-02 02:00:00","2013-01-03 02:00:00")
Parameter<-c("Par1","Par1","Par1","Par2","Par2","Par2")
conc<-c(1,4,3,2,6,5)
obs<-data.frame(Date,Parameter,conc)
obs$Date<-as.POSIXct(obs$Date)
obs$Parameter<-as.factor(obs$Parameter)
obs$conc<-as.numeric(obs$conc)

我需要获取周期2.-3.01.2013的参数值,并将仅那些日期的浓度值乘以5。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

我们可以创建两个日期之间的日期序列,找出与它们重叠的行索引,然后将这些conc值乘以5。

inds <- as.Date(obs$Date) %in% seq.Date(as.Date("2013-01-02"), 
                               as.Date("2013-01-03"), by = "day")
obs$conc[inds] <- obs$conc[inds] * 5

obs
#                 Date Parameter conc
#1 2013-01-01 02:00:00      Par1    1
#2 2013-01-02 02:00:00      Par1   20
#3 2013-01-03 02:00:00      Par1   15
#4 2013-01-01 02:00:00      Par2    2
#5 2013-01-02 02:00:00      Par2   30
#6 2013-01-03 02:00:00      Par2   25