使用R中的软代码从其他后台txt文件更新文本文件中的值

使用R中的软代码从其他后台txt文件更新文本文件中的值,r,optimization,dataframe,text,R,Optimization,Dataframe,Text,我们有这个密码。但该代码需要在每个步骤进行手动输入。我们不能运行数千次或超过10000次来获得最佳变量值。所以我们需要一个从txt文件中读取这些值的代码,我们将在最后根据给定的代码创建这些值。当我给它一个命令时,它从第1行读取变量值,如果我要求读取第2行,它从第2行读取变量值。请帮帮我 dat <- readLines("G:/Rlearning/HYDRUS1D.txt") replaceFn <- function(phrase, value, file){ line &

我们有这个密码。但该代码需要在每个步骤进行手动输入。我们不能运行数千次或超过10000次来获得最佳变量值。所以我们需要一个从txt文件中读取这些值的代码,我们将在最后根据给定的代码创建这些值。当我给它一个命令时,它从第1行读取变量值,如果我要求读取第2行,它从第2行读取变量值。请帮帮我

dat  <-  readLines("G:/Rlearning/HYDRUS1D.txt")
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)
下面给出了编写变量数据的代码

W<- c(3:5)
U<-c(5:7)
H<-c(6:8)
S<-(9:11)
d <-data.frame(W, U, H, S)
write.table(d, "m.txt", row.names =FALSE, quote = FALSE, col.names = TRUE, sep = "\t")
file.show("m.txt")

W根据您对需要做的事情的最新描述,现在这可能会更好

# Load required libraries
library(dplyr)
library(tidyr)

# Set the file paths
HD.txt.path <- file.path("G:/Rlearning/HD.txt")
HYDRUS.path <- file.path("G:/Rlearning/HYDRUS1D.txt")

# Open connection to HD.txt
fileConn <- file(HD.txt.path, open="a")

# Set values to be inserted to HD.txt
HV <- rep(4)
WF <- rep(0, 5)
ST <- rep(0, 5)
U1 <- rep(0, 5)
U2 <- rep(0, 5)
HP <- rep(0, 5)
HT <- rep(0, 5)
EA <- rep(0, 5)
MI <- rep(0, 5)
RU <- rep(0, 5)
RG <- rep(0, 5)
MN <- rep(0, 5)
SN <- rep(0, 5)
SU <- rep("cm",5)
TU <- rep("days",5)
PT <- rep(160,5)
NS <- rep(0, 5)
IC <- rep(1, 5)
NN <- rep(101, 5)
PD <- rep(1.2E+02, 5)
ON <- rep(0,5)
GV <- rep(0,5)
SG <- rep(0,5)
PW <- rep(0,5)
LM <- rep(0,5)
OX <- rep(0,5)
OY <- rep(0,5)
DX <- rep(5.E+00, 5)
DY <- rep(5.E+00, 5)

# Create dataframe of values
mydata <-data.frame(HV,WF,ST,U1,U2,HP,HT,EA,MI,RU,RG,MN,SN,SU,TU,PT,NS,IC,NN,PD,ON,GV,SG,PW,LM,OX,OY,DX,DY)

# Insert values to HD.txt
write.table(mydata, file = fileConn, row.names =FALSE, quote = FALSE, col.names = FALSE, sep = "\t")

# Close connection
close(fileConn)

# Open HD.txt
file.show(HD.txt.path)

# Read in the values from HD.txt
df.hd <- as.data.frame(readLines(HD.txt.path))

# Read the HYDRUS1D file structure and store as template
template <- as.data.frame(readLines(HYDRUS.path))

# Set column name
colnames(template) <- "Variable"

# Split dataframe into Variables and Values
template <- template %>% 
  separate(Variable,into=c("Variable","Value"),sep="=",convert=TRUE,extra="merge",fill="right")

# Create variable aliases to match with HD.txt values
Alias <- c(NA,NA,"HV","WF","ST","U1","U2","HP","HT","EA","MI","RU","RG","MN","SN","SU","TU","PT","NS","IC",NA,NA,"NN","PD","ON","GV","SG","PW","LM","OX","OY","DX","DY")

# Add aliases to the template dataframe
template <- cbind(template, Alias)

# Create the replaceFn
replaceFn <- function(phrase, value, file)
{
  # Replace the specified values
  file <- file %>%
    mutate(Value = ifelse(Alias == phrase,value,Value))

  return(file)
}

# Create a function to handle reading data, which takes a row number as input into the variable i
read.data <- function(i)
{
  # Create a new dat dataframe from the template dataframe
  dat <- template

  # Assign each value from the current row of HD.txt to the dataframe
  for(c in 1:ncol(df.hd))
  {
    dat <- replaceFn(colnames(df.hd)[c], df.hd[i,c], dat)
  }

  # Merge the data into a single output column with variables and values separated by =
  dat <- dat %>%
    mutate(Output = case_when(!is.na(.$Value) ~ paste(.$Variable,.$Value,sep = "="),
                              TRUE ~ .$Variable)) %>%
    select(Output)

  # Write values out to text file
  write.table(dat, HYDRUS.path, row.names =FALSE, na = "", quote = FALSE, col.names = FALSE)

  # Open HYDRUS file
  file.show(HYDRUS.path)

  # If not the last row of HD.txt then prompt to continue
  if(i != nrow(df.hd))
  {
    continue <- readline("Would you like to continue (y/n)?")
    if (tolower(substr(continue, 1, 1)) == "n")
    {continue <- FALSE}
    else if (tolower(substr(continue, 1, 1)) == "y")
    {
      continue <- TRUE
    }
  }

  return(continue)
}

continue <- TRUE

# Loop until continue == FALSE
while(continue == TRUE)
{
  invalid <- TRUE
  # Loop until invalid == FALSE
  while(invalid == TRUE)
  {
    # Retrieve input from user
    rownum <- readline("Enter a row number to process. (Enter 0 to loop through all rows):")

    # Convert input to numeric
    rownum <- suppressWarnings(as.numeric(rownum))
    # Make sure input is not NA, and is a valid row of df.hd
    if(!is.na(rownum) & rownum >= 0 & rownum <= nrow(df.hd))
      # Set invalid to FALSE
      {invalid <- FALSE}

    # Print error if input is invalid
    if(invalid == TRUE)
      {print(paste("Invalid input! Please enter a number from 0 through", nrow(df.hd)))}
  }

  # If user has selected 0
  if(rownum == 0)
  {
    # Loop through each row of HD.txt data
    for(i in 1:nrow(df.hd))
    {
      # Create HYDRUS1D.txt for current row
      continue <- read.data(i)
      if(continue == FALSE)
      {break}
    }
  }
  else
  {
    # Create HYDRUS1D.txt for specified row
    continue <- read.data(rownum)
  }
}
#加载所需的库
图书馆(dplyr)
图书馆(tidyr)
#设置文件路径

HD.txt.path我编写了这段代码,但不是很好的代码。它需要在中间输入行。这里一个朋友写的代码不起作用。如果能成功,那就太好了。因为它只是要求在末尾输入行。我希望他能做得很好。他不是在观察

lfz <- as.data.frame(readLines("G:/Rlearning/wrds.txt"))

lfz或者我们可以grep等号(=)并更改其他文本文件中的列的值,然后按顺序分配给此处。U没有按照我的问题进行操作。我想更新HYDRUS.txt文件中的值。它将从m.txt读取值。它读取行或我们可以创建列,它将更新HYDRUS.txt文件值@Matt Jewett我想更新HYDRUS.txt文件中等号(=)后的值。为此,我有一个包含所需值的文件(m.txt)。我们可以根据需要制作m文件。它可以是数千行或数千列。我们可以这样做,因为HYDRUS.txt文件可以轻松获取其值。它更新了HYDRUS文件。但我有两个问题。首先,它在每个值前面加上=号,例如,它在后面指定相等的符号;和[Main]=这不是必需的。第二个问题是如何更改d.f,使其读取每个变量的第二行。非常感谢你这么做。我将尝试学习这个代码。我只是学习R.m.txt文件是表格。我用write.table创建了它,我修改了答案中的代码,以解决输出问题。我不确定当你说只想读取每个变量的第二行时,你的意思是什么。您是否试图使其自动读取第一行和第二行,然后提示继续每行?
lfz <- as.data.frame(readLines("G:/Rlearning/wrds.txt"))
HYDRUS_Version=
WaterFlow=
.
.
.
.
GridDX=
GridDY=

#creating input file for HYDRUS1D input file
#table of all variable after = sign
fileConn <- file("HD.txt", open="a")
HV<- rep(5, 5)
WF<-rep(0, 5)
ST<-rep(0, 5)
U1<-rep(0, 5)
U2<-rep(0, 5)
HP<-rep(0, 5)
HT<-rep(0, 5)
EA<-rep(0, 5)
MI<-rep(0, 5)
RU<-rep(0, 5)
RG<-rep(0, 5)
MN<-rep(0, 5)
SN<-rep(0, 5)
SU <-rep("cm",5)
TU<-rep("days",5)
PT<- rep(160,5)
NS <-rep(0, 5)
IC <- rep(1, 5)
NN <- rep(101, 5)
PD<- rep(1.2E+02, 5)
ON<- rep(160,5)
GV<- rep(160,5)
SG<- rep(160,5)
PW<- rep(160,5)
LM<- rep(160,5)
GX<- rep(160,5)
GY<- rep(160,5)
Gx<- rep(160,5)
Gy<- rep(160,5)
mydata <-data.frame(HV,WF,ST,U1,U2,HP,HT,EA,MI,RU,RG,MN,SN,SU,TU,PT,NS,IC,NN,PD,ON,GV,SG,PW,LM,GX,GY,Gx,Gy)
write.table(mydata, file = fileConn, row.names =FALSE, quote = FALSE, col.names = FALSE, sep = "\t")
close(fileConn)

file.show("HD.txt")
#reading the specific row of variables
Nt<- read.table("G:/Rlearning/HD.txt")
R2<-(Nt[3,])

#Change it to clumn
C1 <- as.data.frame(t(R2), col.names=FALSE, row.names=FALSE)


outVec <- gsub("\\s*", "", paste(lfz[,1], C1[,1])) 
writeLines(outVec, "outfile.txt") 

file.show("outfile.txt")

imported_text <- readLines("outfile.txt")

imported_text2 <- c(";","[Main]",imported_text)

final_text <- c(imported_text2[1:20],";","[Profile]",imported_text2[21:length(imported_text2)])

writeLines(final_text, "HYDR.txt")
file.show("HYDR.txt")