2016-11-05 22 views
-4

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中的R

這裏「長度爲零的參數」是dput的結果(頭(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") 

第一列是經度和第二個是緯度,第三個是這一點的降水值。我想要做的是通過這些數據製作地圖,但我不知道如何處理這種格式,所以我想將其更改爲三個矩陣:一個用於經度,一個用於緯度,一個用於降水,還有一個用於降水使用函數image.plot(lon,lat,pre1)製作降水圖。

這是我的腳本:

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) 
} 

但它返回一個像這樣的錯誤:

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

我有嘗試其他方式,但我無法弄清楚error.How我可以修理它?任何援助將不勝感激。

+0

歡迎來到Stack Overflow!要在'r'標籤中共享數據,我們要求你使用'dput()'而不是截圖。通過將指針懸停在'r'標籤上可以找到更多信息。 –

+1

我的猜測與其他猜測不同,但我沒有看到列舉所有猜測的任何觀點。我支持Hack-R的建議來發布'dput(head(e1))',所以我們實際上可以知道問題所在。 –

+0

感謝您的幫助。抱歉提供不明確的信息。這是我第一次在這裏問問題。我會添加更多關於它的信息,並盡我所能來說清楚。再次感謝。 – Xiwen

回答

0

好了,檢查出你的數據,我覺得這是多還是少,你所追求的:

# 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)) 

這是你需要什麼?

+0

當你不知道他想完成什麼時,你怎麼可能聲稱已經修復了他的代碼? –

+0

我想問問題的人一旦看到輸出就能判斷出來。一旦提供了關於殘局的更多信息,我們可以從那裏獲取。當提問者決定這不是他們想要獲得的內容時,我會很樂意刪除/編輯我的答案。 – ira

+0

感謝您的建議。我嘗試了你說的方式,但仍然不能工作。對不起,我沒有說清楚,我已添加有關此問題的更多信息。 – Xiwen