读取文件并替换为变量

时间:2018-07-10 19:06:46

标签: r

我有一个简单的文本文件,如下所示。

Title
this is my data

#1 2(0) 3 
 N0 2 3 5 !  

我想做的就是在下面的循环中用变量 i 替换文本文件中的 N ,然后简单地保存它。

for (i in 1:2) {

f <- readLines(data)

=== Do something here to replace N in the text by each i ===

write.table(f,file="file_name",quote=FALSE)

}

然后我可以获得替换为 N 的文件,但没有任何更改。

有任何提示吗?

2 个答案:

答案 0 :(得分:0)

下面的代码可能会帮助您:

fileName = 'file.txt'    # your source file
mystring = readChar(fileName, file.info(fileName)$size)   # reading the file content

for (i in 1:2) {
    index = as.character(i)
    aux = gsub("N", index, mystring) # replacing N by i
    write(aux,file=paste("file_name", index, sep=""))
    #write.table(aux,file=paste("file_name", index, sep=""),quote=FALSE) # choose the best way to  write
}

结果是:

文件名1

$Title
this is my data

#1 2(0) 3 
7(1) 1(0 2) 3 5 !

文件名2

$Title
this is my data

#1 2(0) 3 
7(1) 2(0 2) 3 5 !

答案 1 :(得分:0)

你在这里

for(i in 1:2){
  f <- readLines("text.txt")
  f <- gsub("N", i, text)
  write.table(f,
          file=paste0("file_name_",i ,".txt"),
          quote=FALSE, 
          row.names = FALSE, 
          col.names = FALSE)
}
相关问题