[英]Using the upper row information to loop the file in R
我想計算每日時間段的積雪量,並添加前一天的信息並編寫簡單的代碼。 數據看起來像這樣
elev = seq(550, 1000, 50)
# Elevation in sequence
D <- read.csv('data.csv', stringsAsFactors=T, header=T)
# Data File
Z <- 550
#Elevation
> head(D)
#Table Data
Date T_min T_max P J_day Prain Psnow **Snow accum**
1 1995/08/01 -4 -2 0.4 213 0.2 0.2 **0.2**
2 1995/08/02 -12 -6 0.0 214 0.0 0.0 **0.2**
3 1995/08/03 -5 2 4.2 215 2.6 1.2 **1.4**
4 1995/08/04 -2 5 3.2 216 3.0 0.2 **1.6**
5 1995/08/05 -8 -3 0.0 217 0.0 0.0 **0.0**
我使用循環在每個高程區域中分配了T_max和T_min以及P snow
C_Temp = array(dim=c(length(D$T_max), length(elev)))
C_Ppt = array(dim=c(length(D$P),length(elev)))
for (i in 1:length(elev)){
C_Temp[,i] = D$T_max - Tg*(elev[i]-Z)}
for (i in 1:length(elev)){
C_Ppt[,i] = D$P*(1+ Pg*(elev[i]-Z))}
同樣,我想使用上表中的代碼來計算將雪和雨分開的積雪量。由於格式不是累加,積雪融化也取決於溫度。
SS<-array(dim=c(length(D$P), length(elev)))
for (i in 1:length(elev)){
SS[i+1]<-PG[i-1]+PG }
其中PG是Psnow,SS是積雪(Snow accum)。
我收到一個錯誤:
暗淡[產品36530]與物體[0]的長度不匹配
我不知道如何使用先前的行信息(即Psnow的0.2)來計算使用循環的第二天的S累積,並且由於文件很大,所以我無法手動執行。
令df
為您的數據幀。 比這可以實現
df
structure(list(Date = structure(c(1L, 2L, 3L, 4L, 5L, 5L, 5L), .Label = c("8/1/1995",
"8/2/1995", "8/3/1995", "8/4/1995", "8/5/1995"), class = "factor"),
T_min = c(-4L, -12L, -5L, -2L, -8L, 8L, -7L), T_max = c(-2L,
-6L, 2L, 5L, -3L, -3L, -3L), P = c(0.4, 0, 4.2, 3.2, 0, 0,
0), J_day = c(213L, 214L, 215L, 216L, 217L, 217L, 217L),
Prain = c(0.2, 0, 2.6, 3, 0, 0, 0), Psnow = c(0.2, 0, 1.2,
0.2, 0, 5, 10), X..Snow = structure(c(2L, 2L, 3L, 4L, 1L,
1L, 1L), .Label = c("**0.0**", "**0.2**", "**1.4**", "**1.6**"
), class = "factor")), .Names = c("Date", "T_min", "T_max",
"P", "J_day", "Prain", "Psnow", "X..Snow"), class = "data.frame", row.names = c(NA,
-7L))
head(df)
# Get all the rows satisfying your condition
df_snow<-subset(df, df$T_min<0)
df_snow
# Get columnwise cumulative sum
df_snow$AccuSnow<-cumsum(df_snow$Psnow)
df_snow
# If you want, you can merge now
df.final<-merge(df, df_snow, all=T)
df.final
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.