【问题标题】:Search for string and replace with another [duplicate]搜索字符串并替换为另一个[重复]
【发布时间】:2019-03-28 12:55:27
【问题描述】:

我有其中一列的数据

         Activity Description             
   --------------------------------------------- 
       Handling &  PNR Movement Charges-FCL        
       Value Added Charges                         
       Container Tracking Charges-FCL              
       Contrainer Ground Rent Charges-FCL          
       Documentation Charges FCL                   
       Insurance Charges-FCL                       
       Seal Charges                                
       Fuel Charges-FCL                            
       Container Movement and Increase Charges-FCL 
       Weighment Charges-FCL                       
       Container Movement and Increase Charges-FCL 

我需要搜索包含“FCL”的字符串并替换没有 FCL 的单词。 前任。保险费-FCL 到保险费,即我不需要字符串 FCL。

我试过下面的代码,

 for (line in file_read$`Activity Description`){
 if (line == "*FCL"){
 new_column <- c(new_column,"*")

它不工作。

我的代码是否正确,或者我需要使用另一个代码脚本进行更改?

谁能帮我解决这个问题?

【问题讨论】:

  • sub("FCL", "", file_read$Activity Description)
  • 你能展示一个更大的数据集吗? FCL 是否总是出现在字符串的末尾,前面有一个破折号?
  • 谢谢它的工作。
  • 真的有用吗?它不会在你的名字中留下破折号吗?
  • @TimBiegeleisen,它用破折号打印,但我怎样才能删除破折号,但字符串有破折号而另一个字符串没有

标签: r


【解决方案1】:

假设FCL 总是出现在您的描述的结尾,前面是破折号、空格或其他一些非字母数字字符,那么这是一种使用以下方法进行替换的安全方法sub:

df$`Activity Description` <- sub("[^[:alnum:]]FCL$", "", df$`Activity Description`)

【讨论】:

  • 谢谢它正在工作,但是如果破折号出现在名为 FCL 的字符串中,如何删除破折号?
  • 这会将-FCL 替换为空字符串。不知道你在问什么。第三次,请使用完整的示例数据更新您的问题。
  • 谢谢,它有效,我没有正确检查。
猜你喜欢
  • 2020-01-06
  • 2012-07-17
  • 2022-08-17
  • 2014-06-16
  • 2014-06-23
  • 1970-01-01
  • 1970-01-01
  • 2018-06-16
  • 1970-01-01
相关资源
最近更新 更多