R数据读取和绘图

时间:2017-04-23 05:42:04

标签: r database optimization plot split

我是R for Hydrological Modelling的学习者。我有readLines读取的平面文件,我想要grep并绘制值。这些值是在数千个时间间隔内,但算法只是将值与时间0到9进行绘制。这是代码

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)

当我将字符转换为数字时,问题就开始了,一位专家在几天前在这里做了这个问题,但是没有得到准确的要求。

我是新人,我试图提出这个问题并且无法解决。我希望我能从这个网站上了解更多信息。

1 个答案:

答案 0 :(得分: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作为变量可能会导致问题。