代码之家  ›  专栏  ›  技术社区  ›  maximusdooku

如何用固定宽度值替换字符串?

  •  0
  • maximusdooku  · 技术社区  · 7 年前

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

    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   
    

    我该怎么做?

    2 回复  |  直到 7 年前
        1
  •  0
  •   maximusdooku    7 年前

    non-solution 有效的方法是:

    使所有占位符大小相等。为其他解决方案保持开放。

    T 0 TEMPMW1SS    25.000   500.000 .10  
    T 0 TEMPMW2SS    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   
    
        2
  •  0
  •   MKR    7 年前

    一个选项可以是在列中填充值, space 使一列中的所有值的宽度与该列中最大字符长度的宽度相同。

    使用的解决方案 dplyr 可以是:

    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
    

    数据:

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