r - 如何用固定宽度值替换字符串?
问题描述
我有一个这种格式的文件。
F 0 0.700 99.000 -99.000 .10
T 0 TEMPMW1 25.000 500.000 .10
T 0 TEMPMW2 50.000 5000.000 .10
T 0 0.500 0.050 0.950 .10
T 0 0.500 0.050 0.950 .10
T 0 0.500 0.050 0.950 .10
我想用循环中的值替换变量,但从左起不要超过 13 个字符。
格式基本上是:(L1,1X,I1,1X,3(F9.3,1X)
现在
x1 = 370.1164442
x2 = 4651.9392221
这样做
readLines(paramTemplate) %>% #Reads the template file and replaces the placeholders
gsub(pattern = "TEMPMW1", replace = format(x1, width=9, justify='none', nsmall=3, digits=3)) %>%
gsub(pattern = "TEMPMW2", replace = format(x2, width=9, justify='none', nsmall=3, digits=3))
正在取代价值观
F 0 0.700 99.000 -99.000 .10
T 0 370.116 25.000 500.000 .10
T 0 4651.939 50.000 5000.000 .10
T 0 0.500 0.050 0.950 .10
预期结果
F 0 0.700 99.000 -99.000 .10
T 0 370.116 25.000 500.000 .10
T 0 4651.939 50.000 5000.000 .10
T 0 0.500 0.050 0.950 .10
我怎样才能做到这一点?
解决方案
An option can be to pad values in a column with space
such a way that all values of a column has same width as that of maximum character length in that column.
A solution using dplyr
can be as:
library(dplyr)
df %>%
mutate_all(funs(sprintf(paste("%",max(length(as.character(.))),"s"), as.character(.))))
# V1 V2 V3 V4 V5 V6
# 1 FALSE 0 0.700 99 -99 0.1
# 2 TRUE 0 TEMPMW1 25 500 0.1
# 3 TRUE 0 TEMPMW2 50 5000 0.1
# 4 TRUE 0 0.500 0.05 0.95 0.1
# 5 TRUE 0 0.500 0.05 0.95 0.1
# 6 TRUE 0 0.500 0.05 0.95 0.1
Data:
df <- read.table(text =
"F 0 0.700 99.000 -99.000 .10
T 0 TEMPMW1 25.000 500.000 .10
T 0 TEMPMW2 50.000 5000.000 .10
T 0 0.500 0.050 0.950 .10
T 0 0.500 0.050 0.950 .10
T 0 0.500 0.050 0.950 .10")
推荐阅读
- python - 如何在一系列输入中绘制张量流激活函数
- c# - 有可执行文件,但需要识别源代码
- amazon-web-services - AWS EMR 无法从 S3 存储桶中找到映射器文件 - 没有这样的文件或目录
- facebook - Facebook 洞察 API 仅在一周前推出
- reactjs - 用户可以以任何方式看到未渲染的 React 组件吗?
- java - Tomcat 在同一个 JVM 中不能有多个实例,但在同一个物理框内?
- .net - 是否可以从 Web 服务 .asmx 调用 rest api?
- visual-studio - 带有 cmake 的 Cuda
- python - 如何在 python 的循环中创建自定义语句?
- scala - Spark - 将整行传递给 udf,然后在 udf 中获取列名