2017-04-23 141 views
-1

我是一個剛剛學習R的水文模型。我有一個平面文件,讀取readLines,我想grep和繪製值。該值以千計的時間間隔,但algorithim是針對0到9的時間在這裏只是繪製值是代碼R數據讀取和繪圖

library(stringr) 

x <- readLines("D:/Rlearning/Mohsin HYDRUS/Mohsin practice/Balance.out") 

## Find all lines with [T] 
a <- grep("[T]", x, value = T) 
### Find all the lines that also say Time in that subset 
b <- grep("Time", a , value = T) 
#### Remove the first 2 lines in b (they didn't have a watbalR associated with it) 
c <- b[-c(1,2)] 
### Find all WatBalR lines 
d <- grep("WatBalR", x, value = T) 
#### Put them together in a dataframe 
data <- data.frame(time =c, watbalr = d) 
#### Still need to filter numbers from each line don't know how to do it off the top of my head should be able to google it though like "pulling numbers from a string in R" or something. 
#### Hopefully this helps 

# Extract the numeric values from the two character vectors 
# Use sub to omit all the characters before the first digit 
times <- sub("^.+?(\\d)", "\\1", c) 
WatBlaR <- sub("^.+?(\\d)", "\\1", d) 

# convert the characters to numbers 
times <- as.numeric(times) 
WatBlaR <- as.numeric(WatBlaR) 

# plot 
plot(x = times, y = WatBlaR) 

當我轉換的字符數的問題開始,一位專家這樣做是在這裏前幾天但它沒有得到準確的要求。

我是新來的,我試圖問這個問題,但無法。我希望我會從這個網站了解更多。

+0

請您詳細說明預期輸出是什麼?從問題中不清楚你的意思是什麼*我想爲WatBalR *創造時間和第二列的值。你在尋找方法來聚合這些? – iled

+0

非常感謝K..pradeep。你能否寄給我這些讓我的概念清楚的材料?你太棒了。上週我被困在裏面。我正在研究這個模型的優化。我的第一個任務是R中的簡單優化技術。請向我發送我可以執行的軟件包名稱和材料。非常感謝你非常感謝你。現在我將處理完整的文件。 –

+0

請不要濫用評論系統。如果您想提供更多信息,請編輯您的問題。 – iled

回答

0

您需要從提供的字符串中提取數字值。

# Extract the numeric values from the two character vectors 
# Use sub to omit all the characters before the first digit 
times <- sub("^.+?(\\d)", "\\1", c) 
WatBlaR <- sub("^.+?(\\d)", "\\1", d) 

# convert the characters to numbers 
times <- as.numeric(times) 
WatBlaR <- as.numeric(WatBlaR) 

# plot 
plot(x = times, y = WatBlaR) 

enter image description here

一個建議:不要使用c作爲變量名。 c是一個將值組合成向量或列表的函數。使用c作爲變量可能會導致問題。