在 R 中的列名中间插入文本

Insert text in the middle of column names in R

我想在 data.frame

colnames 中的 . 之后插入字符串 "_2010_"
data("iris")

> names(iris)
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"  

期望的输出

[1] "Sepal._2010_Length" "Sepal._2010_Width"  "Petal._2010_Length" "Petal._2010_Width"  "Species"  

帮助?

编辑: 相关问题:现在如何插入字符串 "_2010_" before the . ?

[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length" "Petal_2010_.Width"  "Species"  

我们可以使用 sub 并在 'iris' 的 names 上使用 .(通过使用 grep 子集)。在这里,我们使用捕获组 ((...)) 并替换为反向引用 (\1) 以及新添加的子字符串 (_2010_).

i1 <- grep("[.]", names(iris))
name(iris)[i1] <- sub("([^.]+.)(.*)", "\1_2010_\2", names(iris)[i1])

或者使用单个捕获组,我们匹配一个点 (.\) 后跟字符,直到捕获组中字符串的末尾。将其替换为一个点,后跟子字符串和反向引用。

sub("\.(.*)", "._2010_\1", names(iris))
#[1] "Sepal._2010_Length" "Sepal._2010_Width"  "Petal._2010_Length"
#[4] "Petal._2010_Width"  "Species"      

如果我们需要 . 之前的字符串,只需更改替换中字符串的放置顺序即可

sub("\.(.*)", "_2010_.\1", names(iris))
#[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length"
#[4] "Petal_2010_.Width"  "Species"  

另一种方法是使用 strsplitpaste:

sapply(strsplit(names(iris), "\."), paste, collapse = "_2010_")
[1] "Sepal_2010_Length" "Sepal_2010_Width"  "Petal_2010_Length" "Petal_2010_Width"  "Species" 

你也可以在你喜欢的地方多加一个点:

sapply(strsplit(names(iris), "\."), paste, collapse = "._2010_")
[1] "Sepal._2010_Length" "Sepal._2010_Width"  "Petal._2010_Length" "Petal._2010_Width"  "Species"

sapply(strsplit(names(iris), "\."), paste, collapse = "_2010_.")
[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length" "Petal_2010_.Width"  "Species"

stringr 中的函数 str_replace 非常适合解决这个问题,而且非常容易使用。

library(stringr)
str_replace(names(iris), "\.", "_2010_.")
#[1] "Sepal_2010_.Length" "Sepal_2010_.Width"  "Petal_2010_.Length" 
#[4] "Petal_2010_.Width"  "Species"

如果您希望 . 在第一个 _ 之前,只需将 "._2010_" 放入 str_replace 的语法中即可。我们使用 \. 而不仅仅是 . 因为点已经具有意义,如果我们想专门匹配它,我们需要转义它 (http://regexone.com/lesson/wildcards_dot).