How do I go about in replacing the nth line of a text file in R?
如何更换R中文本文件的第n行?
2 个解决方案
#1
19
To replace the third line of this:
要替换第三行:
$ cat junk.txt
sic transit
gloria mundi
temeo danoas
et dona ferentes
Do this:
> latin = readLines("junk.txt",-1)
> latin[3]="per ardua ad astra"
> writeLines(latin,"junkout.txt")
and get:
$ cat junkout.txt
sic transit
gloria mundi
per ardua ad astra
et dona ferentes
You can writeLines(latin,"junk.txt")
and overwrite the input file if you want.
如果需要,您可以writeLines(拉丁语,“junk.txt”)并覆盖输入文件。
#2
1
I don't know if there is an option to change a specific line in the streaming file (seek in file), although you have the option to read the file , change a column and write the the frame to a file, read, write functions supply you what you need.
我不知道是否有选项可以更改流文件中的特定行(在文件中搜索),尽管您可以选择读取文件,更改列并将帧写入文件,读取,写入功能为您提供所需的功能。
You may also use read.table()
to read the file into a table format, change specific row and then write.table()
您也可以使用read.table()将文件读入表格格式,更改特定行然后再写入.table()
you have options like read.csv()
and write.csv()
and many other options like readLines()
.
你有read.csv()和write.csv()等选项以及readLines()等许多其他选项。
EDIT
Here is a wiki link for file handling in R
这是R中用于文件处理的wiki链接
#1
19
To replace the third line of this:
要替换第三行:
$ cat junk.txt
sic transit
gloria mundi
temeo danoas
et dona ferentes
Do this:
> latin = readLines("junk.txt",-1)
> latin[3]="per ardua ad astra"
> writeLines(latin,"junkout.txt")
and get:
$ cat junkout.txt
sic transit
gloria mundi
per ardua ad astra
et dona ferentes
You can writeLines(latin,"junk.txt")
and overwrite the input file if you want.
如果需要,您可以writeLines(拉丁语,“junk.txt”)并覆盖输入文件。
#2
1
I don't know if there is an option to change a specific line in the streaming file (seek in file), although you have the option to read the file , change a column and write the the frame to a file, read, write functions supply you what you need.
我不知道是否有选项可以更改流文件中的特定行(在文件中搜索),尽管您可以选择读取文件,更改列并将帧写入文件,读取,写入功能为您提供所需的功能。
You may also use read.table()
to read the file into a table format, change specific row and then write.table()
您也可以使用read.table()将文件读入表格格式,更改特定行然后再写入.table()
you have options like read.csv()
and write.csv()
and many other options like readLines()
.
你有read.csv()和write.csv()等选项以及readLines()等许多其他选项。
EDIT
Here is a wiki link for file handling in R
这是R中用于文件处理的wiki链接