使用 R 填充文本文件 [英] Fill in a text file using R

查看:37
本文介绍了使用 R 填充文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的文本文件:

I have a text file of the sort:

"你好,

我有 %d 只狗和 %d 只猫,

I have %d dogs and %d cats,

平均重量分别为 %f 和 %f 公斤..."

which on average weight respectively %f and %f kilograms... "

我正在尝试创建一个将向量作为输入的 R 函数(例如 c(2, 3, 3.4, 2.3))并使用其条目填充 %f 和 %d在文本文件中(按正确的顺序).

I am trying to create an R function that takes as input a vector (for instance c(2, 3, 3.4, 2.3)) and uses its entries to fill the %f and %d in the text file (in the correct order).

这应该很简单,但我找不到合适的方法做吧.谢谢!

This should be quite straightforward, but I can't find a proper way to do it. Thanks!

推荐答案

如果您可以使用 brew 包语法编写模板,您可以这样做:

If you can write your template using brew package syntax you can do this:

I have <%= ndogs %> dogs and <%= ncats %> cats which on
average weight <%= dogweight/ndogs %> and <%= catweight/ncats %> kg
respectively

然后安装 brew,然后执行:

then install brew, and do:

require(brew)
dogweight=23
catweight=12
ncats=4
ndogs=2
brew("animals.txt")

产生:

I have 2 dogs and 4 cats which on
average weight 11.5 and 3 kg
respectively

您可以将其发送到另一个文件或将其作为文本捕获到 R 中.

which you can send to another file or capture as text into R.

您还可以在模板中进行循环.没有像 sprintf 这样的 8192 个字符限制.

You can also do loops in the template. There's no 8192 character limit like sprintf.

这篇关于使用 R 填充文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆