R - 使用循环向DF添加列

时间:2017-11-24 13:19:45

标签: r calculated-columns

我编写了一个代码,该代码在特定的时间间隔内寻找最小值(例如,每次观察前60秒和每次观察后60秒)。现在我需要编写一个循环,将时间间隔再增加60秒。需要将新迭代的结果(最小值)作为新列添加到数据框中。总而言之,在i = 5的循环中,需要创建5个新列。

我不知道如何添加填充每次迭代结果的新列。

感谢您的帮助。

这是我的示例代码:

df <- data.frame(timestamp = ymd_hms("2017-11-24 08:00:00", "2017-11-24 08:01:00", "2017-11-24 08:02:00", "2017-11-24 08:03:00", "2017-11-24 08:04:00", "2017-11-24 08:05:00", "2017-11-24 08:06:00", "2017-11-24 08:07:00", "2017-11-24 08:08:00", "2017-11-24 08:09:00", "2017-11-24 08:10:00"),
temp=c(99.1, 98.2, 97.0, 96.5, 98.0, 97.6, 99.4, 98.2, 96.4, 99.2, 98.5))`

library(purrr)
library(dplyr)

timeinterval <- 60 

for (i in 1:5) {
timeinterval <- timeinterval+60

mdf <- map(1:nrow(df), ~df[df$timestamp >= df[.x,]$timestamp-timeinterval & df$timestamp <= df[.x,]$timestamp+timeinterval,])
statdf <- map_df(mdf, ~.x %>%  
                          summarise(timestamp_to = tail(timestamp,1),
                timestamp_from = head(timestamp,1),
                                    min.temp = min(temp),
                records = n()))
}
new<-cbind(df, statdf$min.temp)

我认为cbind应该位于循环内部..

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

df <- data.frame(timestamp = ymd_hms("2017-11-24 08:00:00", "2017-11-24 08:01:00", "2017-11-24 08:02:00", "2017-11-24 08:03:00", "2017-11-24 08:04:00", "2017-11-24 08:05:00", "2017-11-24 08:06:00", "2017-11-24 08:07:00", "2017-11-24 08:08:00", "2017-11-24 08:09:00", "2017-11-24 08:10:00"),
                 temp=c(99.1, 98.2, 97.0, 96.5, 98.0, 97.6, 99.4, 98.2, 96.4, 99.2, 98.5))
timeinterval <- 60
n<-5 #number of intervals

f<-function(i){
  timeinterval2 <- timeinterval*i

  mdf <- map(1:nrow(df), ~df[df$timestamp >= df[.x,]$timestamp-timeinterval2 & df$timestamp <= df[.x,]$timestamp+timeinterval2,])
  statdf <- map_df(mdf, ~.x %>%  
                     summarise(timestamp_to = tail(timestamp,1),
                               timestamp_from = head(timestamp,1),
                               min.temp = min(temp),
                               records = n()))
  return(statdf$min.temp)
}
aux<-sapply(1:n,f)
colnames(aux)<-paste("timeinterval",seq(1,n),sep="_")
cbind(df,aux)