Xiwen Xiwen - 1 month ago 6
R Question

"Argument of length zero" in R

I have a data like this and i dont know how to make plot with it, so i wirte a script to change to another form

And here is the result of dput(head(e1)):

structure(list(lon = c(-26.583, -26.25, -26.417, -67.25, -67.25,
-67.417), lat = c(-59.083, -58.417, -58.417, -55.917, -55.75,
-55.75), pre1 = c(105.4, 106.3, 106.6, 73.1, 68.7, 70.2)), .Names = c("lon",
"lat", "pre1"), row.names = c(NA, 6L), class = "data.frame")


The first column is longitude and the second one is latitude, the third one is precipitation value of this point. What i want to do is make a map by this data, but i dont know how to deal with this format, so i want to change it to three matrix: one for longitude,one for latitude, one for precipitation, and than i can use the function image.plot(lon,lat,pre1) to make a map of precipitation.

This is my script:

rerange<-function(e1) {
latq<-sort(e1$lat,decreasing = T)
latq<-as.matrix(latq)
latq1<-unique.matrix(latq)
lonq<-sort(e1$lon)
lonq<-as.matrix(lonq)
lonq1<-unique.matrix(lonq)
lenlon<-length(lonq1)
lenlat<-length(latq1)
finalq<-matrix(0,lenlon,lenlat)
for (i in 1:lenlat) {
for (j in 1:lenlon) {
finalq[i,j]<-e1$pre1[e1$lon == lonq1[j] & e1$lat == latq1[i] ]
}
}
return(finalq)
}


But it return a error like this:

Error in finalq[i, j] <- e1$pre1[e1$lon == lonq1[j] & e1$lat == latq1[i]] :
replacement has length zero


I have try other ways, however I am unable to figure out the error.How i can fix it? Any assistance would be greatly appreciated.

ira ira
Answer

Ok, checking out your data, I think this is more or less what you are after:

# create the dataframe
df <- structure(list(lon = c(-26.583, -26.25, -26.417, -67.25, -67.25, 
                   -67.417), lat = c(-59.083, -58.417, -58.417, -55.917, -55.75, 
                                     -55.75), pre1 = c(105.4, 106.3, 106.6, 73.1, 68.7, 70.2)), .Names = c("lon", 
                                                                                                           "lat", "pre1"), row.names = c(NA, 6L), class = "data.frame")

# change from long to wide format
test <- reshape(df, timevar = "lat", idvar = "lon", direction = "wide")
# turn missing values into zeros
test[is.na(test)] <- 0
# use lon for rownames
rownames(test) <- test[, 1]
# drop the first column
test <- test[,c(2:5)]
# load stringr library
library(stringr)
# drop text from column names
colnames(test) <- str_replace(colnames(test), "pre1.", "")
# put rownames and colnames into increasing order
test <- test[order(rownames(test), decreasing = TRUE), order(colnames(test), decreasing = TRUE)]
test
# load the plotting library
library(fields)
# make the plot
image.plot(as.numeric(rownames(test)), as.numeric(colnames(test)),  as.matrix(test))

Is this what you need?