将矩阵作为表格写入csv文件

时间:2019-08-04 15:40:25

标签: r

我有一个矩阵,它看起来像印刷品:

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

我想将其写入csv文件。

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

它像这样写矩阵:

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

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

也许我应该更改矩阵中不是字符的数据。

我该怎么做?

谢谢

我不想将数据写为向量。应该是:

"1", "2", "3"

"1", "1", "2"

2 个答案:

答案 0 :(得分:3)

data.table的{​​{1}}可以直接处理此问题,因为它可以处理fwrite列,尽管看起来有些奇怪:

list

更漂亮的是使用library(data.table) mat = structure(lapply(1:7, function(i) letters[1:17]), dim = c(7, 1)) # need to set sep to something besides , fwrite(mat, sep2 = c('', ',', ''), sep = '\t') # V1 # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q # a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q 来“翻转”基础transpose

list

答案 1 :(得分:2)

list中的vector通过将matrix包装在其上而直接转换为matrix时,可能会发生这种情况。返回一个matrix,每个元素一个list。例如

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

如果我们这样做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

相反,可以在包装到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" 

或者来自mat本身

simplify2array(mat)

sapply(mat, I)

现在,在'mat2'上使用write.table,应该可以提供预期的输出