我有一个矩阵,我想根据某些“条件”将其融化。
我有2个问题:
1)
我使用make.unique(as.character(colnames(m), sep = ".")
强制将列名和行名强制为唯一,但是将列/行之一保留为3673_2000.1
。
如何在字符串的开头使make.unique
唯一?即1.3673_2000
。
问题1的数据
c("20388_1999", "730464_1999", "1224608_1999", "3370_2000", "3673_2000",
"3673_2000.1", "40493_2000", "69970_2000", "89089_2000", "716823_2000",
"730464_2000", "732718_2000", "746969_2000", "753308_2000", "806085_2000",
"808450_2000", "857005_2000", "899866_2000", "920448_2000", "936340_2000")
[1] "20388_1999" "730464_1999" "1224608_1999" "3370_2000" "3673_2000" "3673_2000.1"
[7] "40493_2000" "69970_2000" "89089_2000" "716823_2000" "730464_2000" "732718_2000"
[13] "746969_2000" "753308_2000" "806085_2000" "808450_2000" "857005_2000" "899866_2000"
[19] "920448_2000" "936340_2000"
这带给我第二个问题: 2)
更正问题1后,我的列和行匹配并具有相似的特征,即后4位是年份。目前,使用melt_m2 <- melt(m)
创建了一个包含400个观测值20
x 20
的数据框。我希望以仅创建15个观测值的方式融化数据。
预期输出:
Var1 Var2 value
1 ID1_2001 ID1_2000 0.7358544
2 ID1_2002 ID1_2001 0.3965007
3 ID1_2003 ID1_2002 0.7358544
4 ID2_2001 ID2_2000 0.9663856
5 ID2_2002 ID2_2001 0.3641962
6 ID2_2003 ID2_2002 0.9663856
7 ID3_2001 ID3_2000 0.1159683
8 ID3_2002 ID3_2001 0.6635743
9 ID3_2003 ID3_2002 0.1159683
10 ID4_2001 ID4_2000 0.5124624
11 ID4_2002 ID4_2001 0.5980401
12 ID4_2003 ID4_2002 0.5124624
13 ID5_2001 ID5_2000 0.4917565
14 ID5_2002 ID5_2001 0.4330341
15 ID5_2003 ID5_2002 0.4917565
因此,它会按年份t
和t-1
合并数据帧。每个ID 2000
的前5个观察值已退出。
数据
m <- matrix(runif(30), nrow = 20, ncol = 20)
dimnames(m) <- list(c(paste0("ID", 1:5, "_2000"), paste0("ID", 1:5, "_2001"), paste0("ID", 1:5, "_2002"), paste0("ID", 1:5, "_2003")),
c(paste0("ID", 1:5, "_2000"), paste0("ID", 1:5, "_2001"), paste0("ID", 1:5, "_2002"), paste0("ID", 1:5, "_2003")))