Reputation: 1798
I have a set of 43 variables/columns named by default as X1, X2, X3.....X46 when I created the dataframe. I need to repace the X's with Q's. Is there a quicker way of doing this in R or must I use the rename() on each X individually? Please help, I want to learn efficient ways of accomplishing this! (I am a novice R programmer)
Upvotes: 1
Views: 3509
Reputation: 655
Assuming df
is your dataframe, e.g.
> df = data.frame(matrix(0,1,43))
you can first empty the current column names, and then name them with any wanted prefix, e.g. "Q"
, using:
> colnames(df)=NULL
> colnames(df)=colnames(df, do.NULL=FALSE, prefix="Q")
Upvotes: 0
Reputation: 9344
names(dataframe) <- gsub("X", "Q", names(dataframe), fixed = TRUE)
The fixed = TRUE
makes it faster because you are not using actual regular expressions.
Upvotes: 6
Reputation: 99321
Assuming cols
is the vector of column names, you can use gsub
to substitute.
> cols
## [1] "X1" "X2" "X3" "X4" "X5" "X6" "X7" "X8" "X9" "X10" "X11" "X12" "X13" "X14"
##[15] "X15" "X16" "X17" "X18" "X19" "X20" "X21" "X22" "X23" "X24" "X25" "X26" "X27" "X28"
##[29] "X29" "X30" "X31" "X32" "X33" "X34" "X35" "X36" "X37" "X38" "X39" "X40" "X41" "X42"
##[43] "X43"
> gsub("X", "Q", cols)
## [1] "Q1" "Q2" "Q3" "Q4" "Q5" "Q6" "Q7" "Q8" "Q9" "Q10" "Q11" "Q12" "Q13" "Q14"
##[15] "Q15" "Q16" "Q17" "Q18" "Q19" "Q20" "Q21" "Q22" "Q23" "Q24" "Q25" "Q26" "Q27" "Q28"
##[29] "Q29" "Q30" "Q31" "Q32" "Q33" "Q34" "Q35" "Q36" "Q37" "Q38" "Q39" "Q40" "Q41" "Q42"
##[43] "Q43"
Upvotes: 2