首页 > 解决方案 > 如何用固定宽度值替换字符串?

问题描述

我有一个这种格式的文件。

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   

我怎样才能做到这一点?

标签: rstringdplyr

解决方案


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")

推荐阅读