Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Running a for loop for renaming column

In my data set, I want to rename my column number 56 to 80. Instead of going manually, I created a list of names that I want the new names to be set as. Then I run a for loop which runs without any error however every single column gets renamed as the last value in the list I created. Any suggestion on what am I doing wrong here. Please see below my code:-

To create the list:-

mylist <- list("Jun-20", "Jul-20", "Aug-20", "Sep-20", "Oct-20", 
    "Nov-20", "Dec-20", "Jan-21", "Feb-21", "Mar-21", "Apr-21", 
    "May-21", "Jun-21", "Jul-21", "Aug-21", "Sep-21", "Oct-21", 
    "Nov-21", "Dec-21", "Jan-22", "Feb-22", "Mar-22", "Apr-22", 
    "May-22", "Jun-22")

And then I run the for loop:-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for (j in 56:80) {
    for (i in 1:length(mylist)) {
        names(CNS7)[j] <- mylist[[i]]
    }
}

Here the j values are the column range (56 to 80) which I want to rename. My end result comes as all the columns from 56 to 80 gets renamed as "Jun-22".

>Solution :

names<- assignment is vectorized i.e. it can assign names to more than one column.

names(CNS7)[56:80] <- unlist(mylist)

Note that colnames or names are all vectors. Therefore, constructing a vector will be more direct

myvec <- c("Jun-20", "Jul-20", "Aug-20", "Sep-20", "Oct-20", 
    "Nov-20", "Dec-20", "Jan-21", "Feb-21", "Mar-21", "Apr-21", 
    "May-21", "Jun-21", "Jul-21", "Aug-21", "Sep-21", "Oct-21", 
    "Nov-21", "Dec-21", "Jan-22", "Feb-22", "Mar-22", "Apr-22", 
    "May-22", "Jun-22")
names(CNS7)[56:80] <- myvec

By doing a nested loop, it is looping over each column in ‘j’, length(mylist) and thus, the names will be changed in each iteration and it gets the value of the last element of ‘mylist’. These are vectorized operations in R and thus doing a nested loop here will result in incorrect results. In addition, it is not efficient (o(n^2))

If we need a loop in (o(n)), create an index object (ind), then loop over the sequence of ‘ind’, subset the ‘ind’ element to get the corresponding names and assign it to list element from the sequence

ind <- 56:80
for(i in seq_along(ind)) {
     names(CNS7)[ind[i]] <- mylist[[i]]
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading