Reputation: 1
I was wondering if anyone can help out with this issue I have.
For example in the iris data, I want to use str_detect to be able to find which columns start with a keyword "Sepal". After finding the columns that start with my keyword, I want to be able to rename all those columns with a number corresponding to when the first column was found. So in the case of the iris data, I want to change "Sepal.Length" and "Sepal.Width" to "S1", "S2", "S3" "..." until the last keyword is found.
I want to be able to replicate this with a dataframe of 100+ variables and to be able to rename 30 of those variables the same way you would with the iris data.
My apologies in advance if my format was off from the normal. I'm new to R /programming so this is all new information for me. Thanks!
Input: str_replace(names(iris), paste0('^\Q', "Sepal", '\E'), '\d+ cBFI')
which gives an output of:
str_replace(names(iris), paste0('^\Q', "Sepal", '\E'), '\d+ S') [1] "d+ S.Length" "d+ S.Width" "Petal.Length" "Petal.Width" "Species"
But what I want is: [1] "S1" "S2" "Petal.Length" "Petal.Width" "Species"
Upvotes: 0
Views: 134
Reputation: 34761
You can do:
library(dplyr)
iris %>%
rename_with(~ paste0("S", seq_along(.x)), starts_with("Sepal"))
S1 S2 Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
...
Upvotes: 1