这是一个双桶电话 题。我有一个数据集文件夹(在 .csv 中),在分析之前需要对其进行更改。每个数据集都是一个 1X10 矩阵,如:
1 2 3 4 5 6 7 8 9 10
并且需要把它变成下面的5X5矩阵,在对角线上插入1:
1
1 1
2 3 1
4 5 6 1
7 8 9 10 1
如何在文件夹中的多个文件上完成这种转换?
最佳答案
尝试这个:
dir.in <- "aaa" # replace with your own input dir
dir.out <- "bbb" # replace with your own output dir
files.in <- list.files(dir.in, full.names = TRUE)
files.out <- file.path(dir.out, basename(files.in))
data.in <- lapply(files.in, scan, sep = ",")
mat.out <- lapply(data.in, function(x){ M <- diag(1, 5)
M[upper.tri(M)] <- x
t(M) })
mapply(write.csv, mat.out, files.out, col.names = FALSE, row.names = FALSE)
关于在 R 中重新排列多个矩阵的形状,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14677485/