string - Insert text in the middle of column names in R -
i insert string "_2010_"
after .
in colnames
of data.frame
data("iris") > names(iris) [1] "sepal.length" "sepal.width" "petal.length" "petal.width" "species"
desired output:
[1] "sepal._2010_length" "sepal._2010_width" "petal._2010_length" "petal._2010_width" "species"
help ?
edit: related question: how insert string "_2010_"
before .
?
[1] "sepal_2010_.length" "sepal_2010_.width" "petal_2010_.length" "petal_2010_.width" "species"
we can use sub
, on names
of 'iris' has .
(by subsetting grep
). here, use capture groups ((...)
) , replace backreferences (\\1
) along newly added substrings (_2010_
).
i1 <- grep("[.]", names(iris)) name(iris)[i1] <- sub("([^.]+.)(.*)", "\\1_2010_\\2", names(iris)[i1])
or using single capture group match dot (.\\
) followed characters until end of string in capture group. replace dot followed substring , backreference.
sub("\\.(.*)", "._2010_\\1", names(iris)) #[1] "sepal._2010_length" "sepal._2010_width" "petal._2010_length" #[4] "petal._2010_width" "species"
if need string before .
change order of placement of strings in replacement
sub("\\.(.*)", "_2010_.\\1", names(iris)) #[1] "sepal_2010_.length" "sepal_2010_.width" "petal_2010_.length" #[4] "petal_2010_.width" "species"
Comments
Post a Comment