2016-06-29 26 views
-1

我有一個大數據框(從2007年到2015年),數據點大約每2分鐘一次。我想繪製每週的圖表(從2007年到2015年),每週都會自動導出爲我的電腦文件夾中的PNG文件。以前,我能夠成功地爲年度,月度和日常情節制作工作代碼。 E.g.for年度數據:R中的每週數據圖

for(j in 2007:2015){ 
mypath <- file.path("~", "Documents","Yearly", paste("WAO_AIR_Data_", j, ".png", sep = "")) 
png(filename = mypath, width = 963, height = 690) 
timePlot(selectByDate(new_subdata, year = j), 
     pollutant = c("CO2", "O2", "APO"), 
     date.pad = TRUE, 
     pch = c(19,19,19), 
     cex = 0.2, 
     xlab = paste("Month of year in", j), 
     ylab = "CO2, O2, and APO concentrations", 
     name.pol = c("CO2 (ppm)", "O2 (per meg)", "APO (per meg)"), 
) 
dev.off() 
} 

數據幀看起來像這樣

tail(new_subdata) 
        date  CO2  O2  APO 
1052042 2015-12-31 23:48:45 409.636 -666.39 -353.27 
1052043 2015-12-31 23:50:46 409.652 -669.62 -356.41 
1052044 2015-12-31 23:52:44 409.679 -669.44 -356.09 
1052045 2015-12-31 23:54:46 409.703 -667.07 -353.59 
1052046 2015-12-31 23:56:44 409.719 -671.02 -357.46 
1052047 2015-12-31 23:58:46 409.734  NA  NA 

但我不知道如何生產每週繪圖代碼。任何人都可以幫助我嗎?非常感謝!

+0

你必須有一個日期變量。 '格式(Sys.Date(),'%​​U%Y')'會給你當前的星期和年份,子集。 – rawr

+0

我的數據框中有一個日期變量列。我不想只想得到本週,我想每個星期從2007年到2015年,每個人都被自動出口到我的電腦 –

+0

@rawr,你能告訴我該怎麼做嗎?謝謝 –

回答

1

通過?strptime,你可以得到一週了DatePOSIXct%U

%U Week of the year as decimal number (00–53) using Sunday as the first day 1 of the week (and typically with the first Sunday of the year as day 1 of week 1). The US convention.

x <- Sys.time() 
class(x); format(x, '%U') 
# [1] "POSIXct" "POSIXt" 
# [1] "26" 

x <- Sys.Date() 
class(x); format(x, '%U') 
# [1] "Date" 
# [1] "26" 

有細微的變化使用的示例數據:

new_subdata <- read.table(header = TRUE, text = "date  CO2  O2  APO 
1052042 '2015-10-31 23:48:45' 409.636 -666.39 -353.27 
1052043 '2015-10-31 23:50:46' 409.652 -669.62 -356.41 
1052044 '2015-11-30 23:52:44' 409.679 -669.44 -356.09 
1052045 '2015-11-30 23:54:46' 409.703 -667.07 -353.59 
1052046 '2015-12-31 23:56:44' 409.719 -671.02 -357.46 
1052047 '2015-12-31 23:58:46' 409.734  NA  NA") 

## create a new grouping variable with year/week 
new_subdata <- within(new_subdata, { 
    yr_wk <- format(as.Date(date), '%Y %U') 
}) 

## iterate over the unique values 
jj <- unique(new_subdata$yr_wk) 
# [1] "2015 43" "2015 48" "2015 52" 

## do some plotting 
par(mfrow = n2mfrow(length(jj)), las = 1, mar = c(5,6,2,2), 
    tcl = .2, mgp = c(3,.25,0)) 
xr <- range(new_subdata$O2, na.rm = TRUE) 
yr <- range(new_subdata$CO2, na.rm = TRUE) 

for (j in jj) { 
    mypath <- file.path("~", "Documents","Yearly", sprintf("WAO_AIR_Data_%s.png", j)) 
    # png(filename = mypath, width = 963, height = 690) 
    plot(CO2 ~ O2, data = subset(new_subdata, yr_wk == j), xlim = xr, ylim = yr) 
    # dev.off() 
} 

myplot

+0

我真的很喜歡你所做的代碼的最後一部分。它使我的代碼更短。感謝您的快速回答:) –

+0

我試圖用opennair包中的timePlot函數來重現您的小時數據代碼。當代碼只有1個數據點時,代碼返回一個錯誤。你能幫我嗎?謝謝! –

+0

@TungLinh以上運行沒有錯誤的例子與一個數據點。什麼是錯誤? – rawr