如何获得与现有矩阵具有相同数据的数据框?
我的矩阵的简化示例:
mat <- matrix(c(0, 0.5, 1, 0.1, 0.2, 0.3, 0.3, 0.4, 0.5),
ncol = 3, nrow = 3,
dimnames = list(NULL, c("time", "C_0", "C_1")))
> mat
time C_0 C_1
[1,] 0.0 0.1 0.3
[2,] 0.5 0.2 0.4
[3,] 1.0 0.3 0.5
Run Code Online (Sandbox Code Playgroud)
我想创建一个如下所示的数据框:
name time val
1 C_0 0.0 0.1
2 C_0 0.5 0.2
3 C_0 1.0 0.3
4 C_1 0.0 0.3
5 C_1 0.5 0.4
6 C_1 1.0 0.5
Run Code Online (Sandbox Code Playgroud)
我所有的尝试都非常笨拙,例如:
data.frame(cbind(c(rep("C_1", 3), rep("C_2", 3)),
rbind(cbind(mat[,"time"], mat[,"C_0"]),
cbind(mat[,"time"], mat[,"C_1"]))))
Run Code Online (Sandbox Code Playgroud)
有没有人知道如何更优雅地做到这一点?请注意,我的实际数据还有一些列(40列).
注意:这不是图形问题.
我有一个nxm矩阵:
> m = matrix(1:6,2,3)
> m
a b c
d 1 2 3
e 4 5 6
Run Code Online (Sandbox Code Playgroud)
我想将其转换为长矩阵:
> m.l
a d 1
a e 4
b d 2
b e 5
c d 3
c e 6
Run Code Online (Sandbox Code Playgroud)
显然嵌套for循环可以工作,但我知道有很多很好的工具可以在R中重构矩阵.到目前为止,我只发现了从长矩阵或宽矩阵转换为nxm矩阵的文献,而不是相反.我错过了一些明显的东西吗 我该怎么做这个转换?
谢谢!
我有这样一张桌子:
A B C D E
7 1 6 8 7
9 3 9 5 9
4 6 2 1 10
10 5 3 4 1
1 3 5 9 3
6 4 8 7 6
Run Code Online (Sandbox Code Playgroud)
我正在查找每个变量与表中每个其他变量的相关性.这是我使用的R代码:
test <- read.csv("D:/AB/test.csv")
iterations <- ncol(test)
correlation <- matrix(ncol = 3 , nrow = iterations * iterations)
for (k in 1:iterations) {
for (l in 1:iterations){
corr <- cor(test[,k], test[,l])
corr_string_A <- names(test[k])
corr_string_B <- names(test[l])
correlation[l + ((k-1) * iterations),] <- rbind(corr_string_A, …Run Code Online (Sandbox Code Playgroud)