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,
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,
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


