【问题标题】:Rearranging the shape of multiple matrices in R在R中重新排列多个矩阵的形状
【发布时间】:2023-03-26 16:54:01
【问题描述】:
这是一个双筒R问题。我有一个数据集文件夹(在 .csv 中),需要在分析之前对其进行更改。每个数据集都是一个 1X10 矩阵,如:
1 2 3 4 5 6 7 8 9 10
并需要将其变成如下对角线插入1的5X5矩阵:
1
1 1
2 3 1
4 5 6 1
7 8 9 10 1
如何对文件夹中的多个文件完成这种转换?
【问题讨论】:
标签:
r
csv
dataset
social-networking
import-from-csv
【解决方案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)