Skip to content

Merge matrices with different column names

2 messages · Charles Determan Jr, arun

#
Hi,

Not sure how you want the results to look like in .csv file.
If "L" is the list of matrices, you can also use ?sink()
sink("L.csv")
L
?sink()


#L.csv output: 
$matrix1 
 
var1 var2 var3 
 
[1 ]    1    4    7 
[2 ]    2    5    8 
[3 ]    3    6    9 
 
 
$matrix2 
 
var4 var5 var6 
 
[1 ]    4    7    3 
[2 ]    3    4    5 
[3 ]    2    3    2 

If you want to do some analysis on the .csv file, you can try this:
new3<-readLines("L.csv")
new4<-new3[!grepl("matrix",new3)]
new5<-gsub("\\[.*\\]","",new4)
do.call(rbind,lapply(lapply(strsplit(new5," "),function(x) paste(unlist(strsplit(x," +")),collapse=" ")),function(x) unlist(strsplit(x,"+ "))))
#???? [,1]?? [,2]?? [,3]? 
#[1,] "var1" "var2" "var3"
#[2,] "1"??? "4"??? "7"?? 
#[3,] "2"??? "5"??? "8"?? 
#[4,] "3"??? "6"??? "9"?? 
#[5,] "var4" "var5" "var6"
#[6,] "4"??? "7"??? "3"?? 
#[7,] "3"??? "4"??? "5"?? 
#[8,] "2"??? "3"??? "2"?? 


#Another way to save the file: 


?out_file <- file("L1.csv", open="a")? 
for (i in seq_along(L)){
??? write.table(names(L)[i], file=out_file, sep=",", dec=".",
quote=FALSE, col.names=FALSE, row.names=FALSE) 
??? write.table(L[[i]], file=out_file, sep=",", dec=".", quote=FALSE,
col.names=NA, row.names=TRUE)? #writes the data.frames
}
close(out_file)? #
new1<-readLines("L1.csv")
?new2<-new1[!grepl("matrix",new1)]
?dat2<-do.call(rbind,lapply(strsplit(new2,","),`[`,2:4))

dat2
#??? [,1]?? [,2]?? [,3]? 
#[1,] "var1" "var2" "var3"
#[2,] "1"??? "4"??? "7"?? 
#[3,] "2"??? "5"??? "8"?? 
#[4,] "3"??? "6"??? "9"?? 
#[5,] "var4" "var5" "var6"
#[6,] "4"??? "7"??? "3"?? 
#[7,] "3"??? "4"??? "5"?? 
#[8,] "2"??? "3"??? "2"?? 


A.K.






----- Original Message -----
From: Charles Determan Jr <deter088 at umn.edu>
To: Dennis Murphy <djmuser at gmail.com>
Cc: r-help at r-project.org
Sent: Friday, October 26, 2012 10:20 AM
Subject: Re: [R] Merge matrices with different column names

Dennis,

This works well and is exactly what I wanted for these matrices.? Thank you
very much, however, when I would try to export the resulting list it just
is bound by columns.? Now this isn't so bad for 2 matrices but I hope to
apply this where there are many matrices and scrolling down a file such as
a 'csv' would be desired.? Any thoughts on exporting a list of matrices?

Thanks,
Charles
On Fri, Oct 26, 2012 at 12:00 AM, Dennis Murphy <djmuser at gmail.com> wrote:

            
??? [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.