【问题标题】:writing multiple lines to a txt file using R使用R将多行写入txt文件
【发布时间】:2014-05-05 13:52:46
【问题描述】:

我试图通过每次更改不同的值来在 txt 中写入多行,并为每次更改创建一个新文件。 我的代码如下所示:

setwd("c:\\Andre\\")#set the working directory
parameter <- read.csv("Parameter_Distribution.csv",header=TRUE)
FSTDEC <- parameter$FSTDEC #the FSTDEC parameter from the table
KBOD20 <- parameter$KBOD20
x <- readLines("1.txt")
m <- readLines("1.txt")

for(y in 1:length(KBOD20))
{
  for(i in 1:length(FSTDEC))
{
  regexp <- "KBOD20"
  Lineno <- grep(pattern = regexp, x = x , value = F) #find the place that have the parameter
  newline1 <- paste("    1    3     ",KBOD20[y],"         1     0.101      1.15",sep='')#the newline for the replacement
  m[Lineno+2] <- newline1 
  regexp <- "FSTDEC"
  Lineno <- grep(pattern = regexp, x = x , value = F)
  newline1 <- paste("    1   17      ",FSTDEC[i],"         1",sep='')
  x[Lineno+2] <- newline1

filename <- paste("Newfiles\\FSTDEC@",FSTDEC[i],".UCI",sep='')
  writelines(x,m,filename) #generate the file with the new file name
  }
}

现在的问题是 writelines 命令,它应该只包含一个文本,然后是文件名。 但是如何将 x 和 m 写入同一个文件并保存为新文件呢?

亲切的问候, 安德烈

【问题讨论】:

    标签: r


    【解决方案1】:

    试试这个:

     Line1 = "Line One of Text File"
     Line2 = "The Second Line of the Text File"
    
    FileName = "TextFile.txt"
    
    fileConn<-file(FileName)
    writeLines(c(Line1, Line2), fileConn)
    close(fileConn)
    

    其中 Line1 和 Line2 是您的前两行。您可以通过添加到这个向量(即 c(Line1, Line2, Line3)

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 2016-01-29
      • 2016-03-02
      • 1970-01-01
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多