在R中使用gsub进行多项更改

时间:2015-06-14 18:12:46

标签: r gsub

我有一个data.frame,我想'清理'列的名称:

>names(Data)
[1] "tBodyAcc.mean...X" 
[2] "angle.X.gravityMean."
[3] "fBodyBodyGyroJerkMag.mean.."
[4] "fBodyAccMag.meanFreq.."
             .
             .

我使用以下代码:

names(Data)<-gsub('[mM]ean',' Mean ',names(Data))
names(Data)<-gsub('[Ff]req',' Frequency ',names(Data))
names(Data)<-gsub('^t','Time  ',names(Data))
names(Data)<-gsub('\\.',' ',names(Data))

获取以下内容:

[1] "Time  BodyAcc  Mean    X"       
[2] "angle X gravity Mean  "         
[3] "fBodyBodyGyroJerkMag  Mean   "  
[4] "fBodyAccMag  Mean  Frequency   "

有没有办法在一行或另一行中表达比这一行更优雅的方式?

3 个答案:

答案 0 :(得分:1)

由于您需要将每个正则表达式应用于完整向量,因此如果没有某种循环,就无法执行此操作。在下面的示例中,n是您的names(Data)向量:

n <- c("tBodyAcc.mean...X", "angle.X.gravityMean.", "fBodyBodyGyroJerkMag.mean..", "fBodyAccMag.meanFreq..")
for(i in seq_along(n)) {
  p <- c('[mM]ean', '[Ff]req', '^t', '\\.')
  r <- c(' Mean ', ' Frequency ', 'Time  ', ' ')
  n <- gsub(p[i], r[i], n)
}

结果:

> n
[1] "Time  BodyAcc  Mean    X"        "angle X gravity Mean  "         
[3] "fBodyBodyGyroJerkMag  Mean   "   "fBodyAccMag  Mean  Frequency   "

答案 1 :(得分:1)

您还可以尝试stri_replace_all_regex包中的stringi

library(stringi)
stri_replace_all_regex(names(Data), c("mean", "freq", "^t", "\\."), c(' Mean ', ' Frequency ', 'Time  ', ' '), F, list(case_insensitive = TRUE))
# [1] "Time  BodyAcc  Mean    X"        "angle X gravity Mean  "         
# [3] "fBodyBodyGyroJerkMag  Mean   "   "fBodyAccMag  Mean  Frequency   "

答案 2 :(得分:1)

你所拥有的已经相当不错,但前两个正则表达式可以使用ignore.case = TRUE进行简化。此外,除了最后一个,我们只想更换一次,最好使用sub代替gsub

nms <- c("tBodyAcc.mean...X", "angle.X.gravityMean.", 
            "fBodyBodyGyroJerkMag.mean..", "fBodyAccMag.meanFreq..")

nms <- sub('mean', ' Mean ', nms, ignore.case = TRUE)
nms <- sub('freq', ' Frequency ', nms, ignore.case = TRUE)
nms <- sub('^t', 'Time  ', nms)
nms <- gsub('\\.', ' ', nms)