Home > other >  Renaming Columns with index with a For Loop in R
Renaming Columns with index with a For Loop in R

Time:11-04

I am writing this post to ask for some advice for looping code to rename columns by index.

I have a data set that has scale item columns positioned next to each other. Unfortunately, they are oddly named.

I want to re-name each column in this format: SimRac1, SimRac2, SimRac3.... and so on. I know the location of the columns (Columns number 30 to 37). I know these scale items are ordered in such a way that they can be named and numbered in increased order from left to right.

The code I currently have works, but is not efficient. There are other scales, in different locations, that also need to be renamed in a similar fashion. This would result in dozens of code rows.

See below code.

names(Total)[30] <- "SimRac1"
names(Total)[31] <- "SimRac2"
names(Total)[32] <- "SimRac3"
names(Total)[33] <- "SimRac4"
names(Total)[34] <- "SimRac5"
names(Total)[35] <- "SimRac6"
names(Total)[36] <- "SimRac7"
names(Total)[37] <- "SimRac8"

I want to loop this code so that I only have a chunk of code that does the work. I was thinking perhaps a "for loop" would help. Hence, the below code

for (i in Total[,30:37]){
names(Total)[i] <- "SimRac(1:8)"
}

This, unfortunately does not work. This chunk of code runs without error, but it doesn't do anything.

Do advice.

CodePudding user response:

In the OP's code, "SimRac(1:8)" is a constant. To have dynamic names, use paste0. We do not need a loop here. We can use a vectorized function to create the names, then assign the names to a subset of names(Total)

names(Total)[30:37]<-paste0('SimRac', 1:8)
  • Related