0

我之前问过一个非常相似的问题,但我得到的答案似乎不适用于这种情况。我的代码的目的主要是获取一个文件,对其进行操作并将操作后的文件保存在旧文件上。不幸的是,有很多文件,所以我合并了一个 for 循环,但它在循环运行一次后就停止了。我认为我的 return 函数在正确的位置,并且我的 for 语句在以前稍微不同的脚本版本中工作。这是我的代码:

AddLatLon<- function(num, condition){


#Set working directiory 
# num is the number of files needing extraction e.g (3:5) , c(2,7)

connect <- file("./EOBS DATA/sources.txt", "r")
locdata <- readLines(connect)
close(connect)

info <- locdata[24:length(locdata)] # removes non data before the data begins



Infodata <- read.table(text = info, sep=',',fill=TRUE,colClasses='character',header ==TRUE )
InfoTable <- read.csv("./EOBS DATA/sources.csv")  
InfoTable$STAID <- as.numeric(InfoTable$STAID)



for(i in c(num)){
filename <-paste("./EOBS DATA/",condition, "_csv_data/", condition,i, ".csv", sep = "")


#if(i <10){
  #filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID00000", i, ".txt", sep = "")
#}
#if(i >=10 & i < 100){
  #filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID0000", i, ".txt", sep = "")
#}

#if(i>= 100 & i <1000){
  #filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID000", i, ".txt", sep = "")
#}
#if(i>= 1000){
  #filename <- paste("./EOBS DATA/ECA_blend_", condition, "/" ,CONDITION, "_STAID00", i, ".txt", sep = "")
#}
if(file.exists(filename) == FALSE) {
  next
}


#con <- file(filename, "r")
#data <- readLines(con)
#close(con)
#q <- data[21:length(data)] # removes non data before the data begins



#Impactdata <- read.table(text = q, sep=',',fill=TRUE,colClasses='character',header = TRUE )


x <- read.csv(filename)



point <- match(i, InfoTable$STAID) 
Lat <- InfoTable[point,5]
Lon <- InfoTable[point,6]

Lat <- as.character(Lat)
Lon <- as.character(Lon)


x$Lat <- Lat
x$Lon <- Lon   



x$X <- NULL
x$DATE<- as.Date(as.character(x$DATE), format='%Y%m%d')

Savename <- paste("./EOBS DATA/",condition, "_csv_data/", condition,i, ".csv", sep = "")   

if(condition == "rr"){
  condition <- "Precipitation"
}
if(condition == "tn"){
  condition <- "Minimum Temperature"
}
if(condition == "tx"){
  condition <- "Maximum Temperature"
}

names(x)<- c("Station_ID", "Source_ID", "Date(yyyy-mm-dd)", condition, "Quality_code(0='valid'; 1='suspect')", "Latitude", "Longitude")


write.csv(x, Savename)


} 
return(head(x))
}
4

1 回答 1

4

num没有定义,但从名字我很确定你想要循环1:num,而不是c(num). 所以只需替换:

for(i in c(num)){

for(i in 1:num)){

或者

for(i in seq_len(num)){

为什么seq_lennum如果为零(无循环)或负数(抛出错误),它将做正确的事情。

于 2013-11-13T12:01:44.927 回答