r - R:如何一次重命名 5 个 data.frames 的列名,每个 35 列?
问题描述
我正在使用下面的 R 代码来模拟时间序列数据,准确地说是 1 阶的移动平均值。我正在改变 3 个变量,它们是:
N = 系列中的元素数c(15L, 20L, 30L, 50L, 100L)
SD = 标准偏差c(1, 2, 3, 4, 5) ^ 2
theta =\theta
值c(0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99)
我有 5 个 data.frames,您将在 R 工作目录中看到 .csv 文件。每个 data.frame 有 35 列我想要正确标记。
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))
我希望 columnname 不仅与 theta 相关,而且与 SD 相关。
我希望将列名标记如下。我不希望 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
解决方案
当您j
在 SD 上迭代(使用 )时,应该这样做:
colnames(ma) <- paste('ma_SD',SD[j],'theta', theta, sep = '_')
推荐阅读
- powershell - PSObject is returning system.object and not a string value
- powershell - 使用 Get-ADGroupMember 列出来自多个 AD 组的成员
- css - 为什么媒体查询不适用
- swiftui - “视图”初始化程序的结果未使用
- angular - 多个模块时Angular库无法导出组件
- html - 在 CSS 中使用“&”选择器的基本原理是什么?
- javascript - 从配置 txt 文件中解析命令行参数
- python - Tkinter 条目获取错误“TypeError:get() 缺少 1 个必需的位置参数:'self'”
- android - 如果在第二个数据类Android Kotlin的一个数据类列表中,则将json转换为对象列表
- android - 如何在 Android 上读取 NFC Snoop Log?