替换列名gsub中的字符

时间:2016-09-23 23:26:45

标签: r gsub

我正在阅读一堆CSV,其中包含"销售 - 数千"在标题中进入R"销售......数千"。我想使用正则表达式(或其他简单方法)来清理它们。

我无法弄清楚为什么这不起作用:

#mock data
  a <- data.frame(this.is.fine = letters[1:5],
                  this...one...isnt = LETTERS[1:5])

#column names
  colnames(a)
  # [1] "this.is.fine"  "this...one...isnt"

#function to remove multiple spaces
  colClean <- function(x){
    colnames(x) <- gsub("\\.\\.+", ".", colnames(x))
  }

#run function
  colClean(a)

#names go unaffected
  colnames(a)
  # [1] "this.is.fine"  "this...one...isnt"

但是这段代码确实:

#direct change to names
  colnames(a) <- gsub("\\.\\.+", ".", colnames(a))

#new names
  colnames(a)
  # [1] "this.is.fine"  "this.one.isnt"

请注意,当发生这种情况时,我会在单词之间留下一段时间。

谢谢。

2 个答案:

答案 0 :(得分:14)

names(a) <- gsub(x = names(a), pattern = "\\.", replacement = "#")  

您可以使用gsub函数将.替换为另一个特殊字符,例如#

答案 1 :(得分:8)

Rich Scriven得到了答案:

定义

func capture(AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?)

然后再做

colClean <- function(x){ colnames(x) <- gsub("\\.\\.+", ".", colnames(x)); x } 

更新