如何在 R 中写入或更改文件中的某些字符?
我有一个 PRM 文件,它是一种文本文件。我想改变其中的一些字符。例如,“md = minf;”到“md = maxf;”和“ls = 1”到“ls = 3”。 你能指导我如何改变它吗?我不知道在这种情况下如何使用 WriteLines 函数?
> setwd("C:/Users/Documents/CONN")
> fileName <- "Hmin.PRM"
> conn <- file(fileName,open="r")
> linn <-readLines(conn)
> for (i in 1:length(linn)){
+ print(linn[i])
+ }
[1] ""
[1] "begin_pop = \"p1\";"
[1] " beginfounder;"
[1] " male [n = 20, pop = \"hp\"];"
[1] " female [n = 400, pop = \"hp\"];"
[1] " endfounder;"
[1] " ls = 1; "
[1] " pmp = 0.5; "
[1] " ng = 10; "
[1] " md = minf; "
[1] " sr = 0.5; "
[1] " dr = 0.3; "
[1] " sd = ebv /h; "
[1] " cd = ebv /l; "
[1] " ebvest = true_av;"
[1] " begpop;"
[1] " ld /maft 0.1;"
[1] "\t crossover;"
[1] " data;"
[1] " stat;"
[1] " genotype/gen 8 9 10;"
[1] " endpop;"
[1] "end_pop;"
[1] " "
> close(conn)
I have a PRM file that is a kind of text file. I want to change some characters in it. For example, " md = minf; " to "md = maxf;" and "ls = 1" to "ls = 3".
Can you guide me on how can I change it? I don't know how can I use WriteLines function in this situation?
> setwd("C:/Users/Documents/CONN")
> fileName <- "Hmin.PRM"
> conn <- file(fileName,open="r")
> linn <-readLines(conn)
> for (i in 1:length(linn)){
+ print(linn[i])
+ }
[1] ""
[1] "begin_pop = \"p1\";"
[1] " beginfounder;"
[1] " male [n = 20, pop = \"hp\"];"
[1] " female [n = 400, pop = \"hp\"];"
[1] " endfounder;"
[1] " ls = 1; "
[1] " pmp = 0.5; "
[1] " ng = 10; "
[1] " md = minf; "
[1] " sr = 0.5; "
[1] " dr = 0.3; "
[1] " sd = ebv /h; "
[1] " cd = ebv /l; "
[1] " ebvest = true_av;"
[1] " begpop;"
[1] " ld /maft 0.1;"
[1] "\t crossover;"
[1] " data;"
[1] " stat;"
[1] " genotype/gen 8 9 10;"
[1] " endpop;"
[1] "end_pop;"
[1] " "
> close(conn)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正则表达式的解释:
\\b
是一个单词边界,所以我们匹配md
但不是amd
;\\s*
是零个或多个空格(..)
是一个匹配组,(在本例中)我们希望将其带回替代品;\\1
正在回忆第一个匹配组,ls =
和3
之间引入空格的唯一原因(而我没有添加maxf
之前的空格)是我希望\\1
和\\13
之间在视觉上绝对没有歧义,建议 13 个匹配组。 R 对后者没有问题,但我想我应该在正则表达式中保持清晰。Explanation of the regex:
\\b
is a word-boundary, so we matchmd
but notamd
;\\s*
is zero-or-more blank-space(..)
is a match-group, which (in this case) we want to bring back in the replacement;\\1
is recalling the first match-groupls =
and3
(whereas I did not add a space beforemaxf
) is that I wanted absolutely no ambiguity visually between\\1
and\\13
suggesting 13 match-groups. R didn't have a problem with the latter, but I thought I'd keep it clear in the regex.