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

Conditional naming of columns in R

Good day,

I’m trying to figure out how to rename columns in R based on a certain set of conditions. Consider the following two examples from the code,

tt <- t(matrix(c(.8,.2,0)))
colnames(tt) <- c("2","3","NA")
tt

tt <- t(matrix(c(.7,.3,0)))
colnames(tt) <- c("1","3", "NA")
tt

Which generate the following two outputs respectively,

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

enter image description here

enter image description here

I want to rename the columns in such a way that "1" should be "AR(1)", "2" should be "AR(2)" "3" should be "ARMA(1,1)" and "NA" would be replaced by whichever number would be missing. So in the case of the first table that was printed "NA" would be replaced with "AR1" thus the final table should look like,

enter image description here

I know that the columns can be renamed using the function colnames as demonstrated in the example code, however I have to generate about 100+ of these types of tables, all of which will have only three names as mentioned before. So if there anyway to set this up using an ifelse statement or another method because I haven’t had much luck with it.

Thank you

>Solution :

Create a function and reuse the function on the datasets

f1 <- function(x)
{
nm1 <- setNames( c("AR(1)", "AR(2)", "ARMA(1,1)"), c("1", "2", "3"))
nm2 <- setdiff(names(nm1), colnames(x))
colnames(x)[colnames(x) == "NA"] <- nm2

colnames(x) <- nm1[colnames(x)]
x


}

-testing

> f1(tt)
     AR(1) ARMA(1,1) AR(2)
[1,]   0.7       0.3     0
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