如何在R?
中将矩阵列表写入csv文件我试过
fff = tr[[3]]
MATweight = ldply(fff, function(t) t$toDataFrame())
但有这个错误
Error in t$toDataFrame : $ operator is invalid for atomic vectors
我不确定这是否是正确的做法,请问任何想法?
我有这个矩阵列表
> str(fff)
List of 10
$ : num [1:1000, 1:50] 1 1 1 1 2 2 1 2 2 1 ...
....
$ : num [1:1000, 1:50] 1 1 1 1 2 2 1 2 2 1 ..
当我尝试G的建议答案时,我得到了:
> write.csv(map_dfr(fff, as.data.frame, .id = "matrix"),"testt.csv", row.names = FALSE)
> tgtg = read.csv("/Users/amani/testt.csv")
> str(tgtg)
'data.frame': 10000 obs. of 51 variables:
$ matrix: int 1 1 1 1 1 1 1 1 1 1 ...
$ V1 : int 1 1 1 1 2 2 1 2 2 1 ...
$ V2 : int 2 2 1 2 1 1 2 1 1 2 ...
$ V3 : int 1 1 1 1 1 2 1 1 2 1 ...
....
$ V50 : int 2 2 1 1 1 1 1 1 2 2 ...
答案 0 :(得分:2)
使用显示的L
测试数据,从purrr:
map_dfr
library(purrr)
L <- list(as.matrix(BOD), as.matrix(10*BOD)) # test data
write.csv(map_dfr(L, as.data.frame, .id = "matrix"), stdout(), row.names = FALSE)
,并提供:
"matrix","Time","demand"
"1",1,8.3
"1",2,10.3
"1",3,19
"1",4,16
"1",5,15.6
"1",7,19.8
"2",10,83
"2",20,103
"2",30,190
"2",40,160
"2",50,156
"2",70,198
答案 1 :(得分:0)
为什么不这样做:
# sample data like your `fff` list of matrices
fff <- lapply(1:10, function(i)
matrix(data = sample(1:2, 510000, replace = TRUE), nrow = 10000, ncol = 51))
# we give each matrix in the list a unique name
mat_names <- as.character(1:length(fff))
# converting to dataframe with the list index preserved
fffdf <- lapply(1:length(fff), function(i)
cbind(mat_names = mat_names[i], as.data.frame(fff[[i]])))
fffdf <- do.call(rbind, fffdf)
# writing it to a file
t <- tempfile(fileext = ".csv")
write.csv(fffdf, t, row.names = FALSE)
# testing the reassembly into the same list of matrices that you started
tcsv <- read.csv(t)
tgtg <- lapply(mat_names, function(i) {
df <- subset(tcsv, mat_names == i, select = -mat_names)
mat <- as.matrix(df)
dimnames(mat) <- NULL
return(mat)
})
测试结果:tgtg
与您开始的fff
相同吗?
> identical(fff, tgtg)
[1] TRUE
> str(tgtg)
List of 10
$ : int [1:10000, 1:51] 1 2 1 2 1 1 2 2 1 1 ...
$ : int [1:10000, 1:51] 2 2 2 2 2 2 1 1 1 1 ...
$ : int [1:10000, 1:51] 1 2 1 1 2 2 1 1 2 1 ...
$ : int [1:10000, 1:51] 1 1 2 2 1 1 1 2 1 1 ...
$ : int [1:10000, 1:51] 1 1 2 1 2 2 1 1 1 2 ...
$ : int [1:10000, 1:51] 2 1 2 2 1 1 1 2 1 2 ...
$ : int [1:10000, 1:51] 2 1 2 1 2 1 1 1 2 1 ...
$ : int [1:10000, 1:51] 2 2 1 1 2 2 1 2 1 1 ...
$ : int [1:10000, 1:51] 1 2 1 1 1 1 1 2 2 1 ...
$ : int [1:10000, 1:51] 1 1 1 2 2 2 2 2 2 2 ...