Search code examples
rr-colnames

R: How can one rename columnname of 5 data.frames with 35 columns each at once?


I am using the below R code to simulate time series data, moving average of order 1 to be precise. I am varying 3 variables which are:

N = Number of elements in the series c(15L, 20L, 30L, 50L, 100L) SD = standard deviation c(1, 2, 3, 4, 5) ^ 2 theta = the \theta value c(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99) I have 5 data.frames which you will see as .csv files in your R working directory. Each data.frame has 35 columns that I want properly labeled.

MWE

N <- c(15L, 20L, 30L, 50L, 100L)
SD = c(1, 2, 3, 4, 5) ^ 2
theta = c(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)

res <- vector('list', length(N))
names(res) <- paste('N', N, sep = '_')

set.seed(123L)
for (i in seq_along(N)){
  res[[i]] <- vector('list', length(SD))
  names(res[[i]]) <- paste('SD', SD, sep = '_')

  ma <- matrix(NA_real_, nrow = N[i], ncol = length(theta)) 

  for (j in seq_along(SD)){
    wn <- rnorm(N[i], mean = 0, sd = SD[j])
    ma[1:2, ] <- wn[1:2]

    for (k in 3:N[i]){
      ma[k, ] <- wn[k - 1L] * theta + wn[k]
        }
    colnames(ma) <- paste('ma_theta', theta, sep = '_')
    res[[i]][[j]] <- ma
  }
}

res1 <- lapply(res, function(dat) do.call(cbind,  dat))
sapply(names(res1), function(nm) write.csv(res1[[nm]], 
                                       file = paste0(nm, ".csv"), row.names = FALSE, quote = FALSE))

I want columnname to be label not only with respect to theta alone but also with SD.

I want the columnname to be labelled like the below. I do not want 2 or more columns to have the same label. I want ma_SD_1... to (with theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)) be exhausted before ma_SD_4... (with theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)) before ma_SD_9... (with theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)) before ma_SD_16... (with theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)) before ma_SD_25... (with theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)).

ma_SD_1_theta_0.2, ma_SD_1_theta_0.4, ma_SD_1_theta_0.6, ma_SD_1_theta_0.8, ma_SD_1_theta_0.9, ma_SD_1_theta_0.95, ma_SD_1_theta_0.99

ma_SD_4_theta_0.2, ma_SD_4_theta_0.4, ma_SD_4_theta_0.6, ma_SD_4_theta_0.8, ma_SD_4_theta_0.9, ma_SD_4_theta_0.95, ma_SD_4_theta_0.99

ma_SD_9_theta_0.2, ma_SD_9_theta_0.4, ma_SD_9_theta_0.6, ma_SD_9_theta_0.8, ma_SD_9_theta_0.9, ma_SD_9_theta_0.95, ma_SD_9_theta_0.99

ma_SD_1_theta_0.2, ma_SD_16_theta_0.4, ma_SD_16_theta_0.6, ma_SD_16_theta_0.8, ma_SD_16_theta_0.9, ma_SD_16_theta_0.95, ma_SD_16_theta_0.99

Solution

  • This should do it as you are iterating (using j) over the SD:

    colnames(ma) <- paste('ma_SD',SD[j],'theta', theta, sep = '_')