q1:r中读入csv文件时,读入所有的列合并为一列
A1:此时因为保存时是write.table(),,所以读入直接read.table就行,什么参数也别加,,,如果不是直接保存的测试v、文件的话,读入用read.csv(),参数要加header = T,sep = ','
r包下载地方:
The downloaded source packages are in
‘/tmp/Rtmp1UrAkM/downloaded_packages’
安装位置:~/R/x86_64-pc-linux-gnu-library/4.0(服务器)
library(Matrix)
M <- Matrix(c(0, 0, 0, 2,
6, 0, -1, 5,
0, 4, 3, 0,
0, 0, 5, 0),
byrow = TRUE, nrow = 4, sparse = TRUE)
rownames(M) <- paste0("r", 1:4)
colnames(M) <- paste0("c", 1:4)
M
# 4 x 4 sparse Matrix of class "dgCMatrix"
# c1 c2 c3 c4
# r1 . . . 2
# r2 6 . -1 5
# r3 . 4 3 .
# r4 . . 5 .
认识dgcMatrix
str(M)
# Formal class 'dgCMatrix' [package "Matrix"] with 6 slots
# ..@ i : int [1:7] 1 2 1 2 3 0 1
# ..@ p : int [1:5] 0 1 2 5 7
# ..@ Dim : int [1:2] 4 4
# ..@ Dimnames:List of 2
# .. ..$ : chr [1:4] "r1" "r2" "r3" "r4"
# .. ..$ : chr [1:4] "c1" "c2" "c3" "c4"
# ..@ x : num [1:7] 6 4 -1 3 5 2 5
# ..@ factors : list()
x:矩阵中的数字,第一列非0的数字依次写,接着第二列第三列
M
# 4 x 4 sparse Matrix of class "dgCMatrix"
# c1 c2 c3 c4
# r1 . . . 2
# r2 6 . -1 5
# r3 . 4 3 .
# r4 . . 5 .
M@x
# [1] 6 4 -1 3 5 2 5
as.numeric(M)[as.numeric(M) != 0]
# [1] 6 4 -1 3 5 2 5
I: 存储这些非0数字所在的行数,特殊的,第一行为0
M
# 4 x 4 sparse Matrix of class "dgCMatrix"
# c1 c2 c3 c4
# r1 . . . 2
# r2 6 . -1 5
# r3 . 4 3 .
# r4 . . 5 .
M@i
# [1] 1 2 1 2 3 0 1
p:If we index the columns such that the first column has index ZERO, then M@p[1] = 0, and M@p[j+2] - M@p[j+1] gives us the number of non-zero elements in column j.
In our example, when j = 2, M@p[2+2] - M@p[2+1] = 5 - 2 = 3, so there are 3 non-zero elements in column index 2 (i.e. the third column).其实就是每列非0的个数,第一个是0,最后一个是非0的个数,中间依次是前面n列的非0的个数
比如这个M中的p的形成
第一个数字是0 ,最后一个数字是矩阵中非0 的个数,也就是7,那么第二个数字就是第一列中非0的个数(1),第三个数字就是第一列的非0数加第二列的非0数,第四个数字是第三列的非0数加前面所有列的非0数,然后依次加到最后一个
M
# 4 x 4 sparse Matrix of class "dgCMatrix"
# c1 c2 c3 c4
# r1 . . . 2
# r2 6 . -1 5
# r3 . 4 3 .
# r4 . . 5 .
M@p
# [1] 0 1 2 5 7
dims:行数,列数
dimnames:行名,列名
library(Matrix)
m <- Matrix(c(0,0,0,20,5,
2,5,8,0,0,
0,0,0,0,8),
byrow = TRUE,nrow = 3,sparse = TRUE)
rownames(m) <- paste0('r',1:3)
colnames(m) <- paste0('c',1:5)
m
3 x 5 sparse Matrix of class #"dgCMatrix"
# c1 c2 c3 c4 c5
#r1 . . . 20 5
#r2 2 5 8 . .
#r3 . . . . 8
str(m)
#Formal class 'dgCMatrix'
#[package "Matrix"] with 6 slots
# ..@ i : int [1:6] 1 1 1 0 0 2
# ..@ p : int [1:6] 0 1 2 3 4 6
# ..@ Dim : int [1:2] 3 5
# ..@ Dimnames:List of 2
# .. ..$ : chr [1:3] "r1" "r2" "r3"
# .. ..$ : chr [1:5] "c1" "c2" "c3" #"c4" ...
# ..@ x : num [1:6] 2 5 8 20 5 8
# ..@ factors : list()