R:如何一次重命名5个 Dataframe (每个帧有35列)的列名?

wnrlj8wa  于 2023-04-03  发布在  其他
关注(0)|答案(1)|浏览(163)

我使用下面的R代码来模拟时间序列数据,精确地说是1阶移动平均值。我改变了3个变量,它们是:
N =序列中的元素数c(15L, 20L, 30L, 50L, 100L) SD =标准差c(1, 2, 3, 4, 5) ^ 2 theta = \thetac(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)我有5个data.frames,您将在R工作目录中看到它们作为.csv文件。
微波辐射计

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

我希望columnname标签不仅与theta有关,而且与SD有关。
我希望columnname的标签如下所示。我不希望2个或更多列具有相同的标签。我希望ma_SD_1...(使用theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99))在ma_SD_4...(使用theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99))之前在ma_SD_9...(使用theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99))之前在ma_SD_16...(使用theta=(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99))之前在ma_SD_25...(使用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
rsaldnfx

rsaldnfx1#

当你在SD上迭代(使用j)时,这应该可以做到:

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

相关问题