使用R r更改txt文件中的值

时间:2017-05-15 21:18:23

标签: r optimization export requirements.txt

我想写一个软代码,它将改变我的Hydrological模型输入txt文件所需参数的值。一些参数是固定的,有些我会改变观察值。例如,HYDRUS_Version = 4是固定的,WaterFlow = 1,SoluteTransport = 0等是我想要更改其值的参数。我想指定waterFlow = 5或WaterFlow = 3.1和SoluteTransport = 2或= 2.2

的值

我尝试了这个代码用于水流,但我的txt文件中的值没有改变。我只是R的新学习者。

    lines <- readLines("G:/Rlearning/HYDRUS1D.txt")

        library(gsubfn)
        i1 <- grepl("Vertical Conductivity", lines)
        lines[i1] <- gsubfn("[0-9.]+", ~format(as.numeric(x)*2, 
                                           scientific = FALSE), lines[i1])

以下是完整的txt文件。

;
[Main]
HYDRUS_Version=4
WaterFlow=1
SoluteTransport=0
Unsatchem=0
Unsatchem=0
HP1=0
HeatTransport=0
EquilibriumAdsorption=1
MobileImmobile=0
RootWaterUptake=1
RootGrowth=0
MaterialNumbers=1
SubregionNumbers=1
SpaceUnit=cm
TimeUnit=days
PrintTimes=160
NumberOfSolutes=0
InitialCondition=1
;
[Profile]
NumberOfNodes=101
ProfileDepth=1.2E+02
ObservationNodes=5
GridVisible=1
SnapToGrid=1
ProfileWidth=80
LeftMargin=40
GridOrgX=0
GridOrgY=0
GridDX=5.E+00
GridDY=5.E+00

1 个答案:

答案 0 :(得分:0)

创建自定义函数以搜索匹配的字符串并替换值:

replaceFn <- function(phrase, value, file){
  line <- file[grep(phrase, file)]
  value.pos <- as.numeric(gregexpr("=", line))
  file[grep(phrase, file)] <- paste0(substring(line, 1, value.pos), value)
  return(file)
}


dat <- replaceFn("WaterFlow", 3.1, dat)
dat <- replaceFn("SoluteTransport", 2.2, dat)

[1] ";"                       "[Main]"                  "HYDRUS_Version=4"        "WaterFlow=3.1"           "SoluteTransport=2.2"     "Unsatchem=0"            
[7] "Unsatchem=0"             "HP1=0"                   "HeatTransport=0"         "EquilibriumAdsorption=1" "MobileImmobile=0"        "RootWaterUptake=1"      
[13] "RootGrowth=0"            "MaterialNumbers=1"       "SubregionNumbers=1"      "SpaceUnit=cm"            "TimeUnit=days"           "PrintTimes=160"         
[19] "NumberOfSolutes=0"       "InitialCondition=1"      ";"                       "[Profile]"               "NumberOfNodes=101"       "ProfileDepth=1.2E+02"   
[25] "ObservationNodes=5"      "GridVisible=1"           "SnapToGrid=1"            "ProfileWidth=80"         "LeftMargin=40"           "GridOrgX=0"             
[31] "GridOrgY=0"              "GridDX=5.E+00"           "GridDY=5.E+00"   

输入数据:

dat <- c(";", "[Main]", "HYDRUS_Version=4", "WaterFlow=1", "SoluteTransport=0", 
"Unsatchem=0", "Unsatchem=0", "HP1=0", "HeatTransport=0", "EquilibriumAdsorption=1", 
"MobileImmobile=0", "RootWaterUptake=1", "RootGrowth=0", "MaterialNumbers=1", 
"SubregionNumbers=1", "SpaceUnit=cm", "TimeUnit=days", "PrintTimes=160", 
"NumberOfSolutes=0", "InitialCondition=1", ";", "[Profile]", 
"NumberOfNodes=101", "ProfileDepth=1.2E+02", "ObservationNodes=5", 
"GridVisible=1", "SnapToGrid=1", "ProfileWidth=80", "LeftMargin=40", 
"GridOrgX=0", "GridOrgY=0", "GridDX=5.E+00", "GridDY=5.E+00")