Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

r - Subscript out of bounds on list objects (dataframes) identical in size and format

I'm working on creating a drought severity index and currently have the following code to produce monthly drought severity index (PDSI) values for each of 160 sites:

library(scPDSI)
library(SPEI)
library(datasets)
library(plyr)

#PDSI CALCULATIONS
All_data <- read.csv("https://raw.githubusercontent.com/gbream/MS_Research/main/Climate_Lat_PET_AWC.csv")

#Splitting into object by Site_ID
Split_all_data <- split(All_data, All_data$Site_ID)

PDSI_161 <- pdsi(P=Split_all_data[[161]]$Prec, PE=Split_all_data[[161]]$PET, AWC = 142.9)

lapply(PDSI_161$X, function(x) write.table(data.frame(x),"161_Final_PDSI_data.csv", sep=",", append=TRUE))

I can individually run any Site_ID below 161 (up to 156) without issue, but when I try any sites numbered 161 or above, I get the following error:

"PDSI_161 <- pdsi(P=Split_all_data[[161]]$Prec, PE=Split_all_data[[161]]$PET, AWC = 142.9) Error in Split_all_data[[161]] : subscript out of bounds"

I understand what the error means, but can't find any reason that it would be giving this error as all of the list objects are identical in size (1476 rows/8 columns) and format. Also, there is no significance to the site number being higher than 156- they are only site ID's. Any help would be appreciated.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually the site ID is not the same as the list index since the ID values seems to be missing numbers (for example no ID between 248 and 261).

If you want your list index to match your site ID you could use a loop to populate a named list instead of split():

Split_all_data = list()   
for(id in unique(All_data$Site_ID)){
    Split_all_data[[as.character(id)]] = All_data[All_data$Site_ID == id,]
}

PDSI_161 <- pdsi(P=Split_all_data[["161"]]$Prec, PE=Split_all_data[["161"]]$PET, AWC = 142.9)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...