Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing matrix as table to csv file

Tags:

r

I have a matrix, it looks in print:

  [,1]        
[1,] Character,17
[2,] Character,17
[3,] Character,17
[4,] Character,17
[5,] Character,17
[6,] Character,17
[7,] Character,17

I want to write it to csv file.

write.table(mat, file = "...", ..)

It writes the matrix like this:

c("1", "2", "3")

c("1", "1", "2")

Maybe I should change the data in the matrix that will not be a character.

How can I do this?

Thanks

I want to write the data not as a vector. It should be:

"1", "2", "3"

"1", "1", "2"
like image 581
Tal Avatar asked Jan 26 '26 22:01

Tal


1 Answers

This could happen when a list of vectors are converted directly to matrix by wrapping matrix on it. Returns a matrix with each element a list. e.g.

set.seed(24)
lst1 <- lapply(1:7, function(x) sample(letters[1:10], 17, replace = TRUE))

If we do matrix

mat <- matrix(lst1)
str(mat)
#List of 7
# $ : chr [1:17] "g" "c" "h" "g" ...
# $ : chr [1:17] "h" "a" "e" "e" ...
# $ : chr [1:17] "c" "a" "c" "h" ...
# $ : chr [1:17] "e" "j" "i" "a" ...
# $ : chr [1:17] "d" "j" "g" "h" ...
# $ : chr [1:17] "b" "b" "a" "h" ...
# $ : chr [1:17] "e" "c" "c" "d" ...
# - attr(*, "dim")= int [1:2] 7 1

mat
#     [,1]        
#[1,] Character,17
#[2,] Character,17
#[3,] Character,17
#[4,] Character,17
#[5,] Character,17
#[6,] Character,17
#[7,] Character,17

Instead, it can be either corrected before wrapping to matrix

mat2 <- simplify2array(lst1)
#or # mat2 <- do.call(cbind, lst1)
mat2
#      [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] "g"  "h"  "c"  "e"  "d"  "b"  "e" 
# [2,] "c"  "a"  "a"  "j"  "j"  "b"  "c" 
# [3,] "h"  "e"  "c"  "i"  "g"  "a"  "c" 
# [4,] "g"  "e"  "h"  "a"  "h"  "h"  "d" 
# [5,] "b"  "e"  "f"  "a"  "c"  "g"  "b" 
# [6,] "c"  "h"  "g"  "a"  "g"  "d"  "b" 
# [7,] "j"  "b"  "a"  "d"  "j"  "e"  "h" 
# [8,] "h"  "a"  "f"  "g"  "j"  "b"  "h" 
# [9,] "f"  "e"  "g"  "c"  "j"  "b"  "g" 
#[10,] "j"  "b"  "a"  "e"  "c"  "b"  "i" 
#[11,] "i"  "a"  "b"  "g"  "h"  "i"  "e" 
#[12,] "d"  "e"  "d"  "e"  "h"  "f"  "e" 
#[13,] "i"  "d"  "c"  "g"  "e"  "d"  "g" 
#[14,] "h"  "j"  "f"  "j"  "j"  "e"  "f" 
#[15,] "g"  "f"  "c"  "h"  "c"  "i"  "j" 
#[16,] "h"  "f"  "d"  "j"  "c"  "i"  "i" 
#[17,] "a"  "j"  "f"  "d"  "a"  "c"  "a" 

Or from the mat itself

simplify2array(mat)

Or

sapply(mat, I)

Now, with write.table on 'mat2', should give the expected output

like image 91
akrun Avatar answered Jan 29 '26 11:01

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!