0

我有 3 列数据:

var1 var2    Z
   1   2    1.2
   3   4    5.4
   1   4    2.3

我想将其转换为如下所示的共存矩阵:

       1   2    3    4
  1    0   1.2  0   2.3
  2    0   0    0   0
  3    0   0    0   5.4
  4    0   0    0   0

有没有办法用 R 语言做到这一点?提前感谢您的宝贵时间。

4

2 回答 2

1

我假设您从 开始data.frame,也许是这样的:

mydf <- structure(list(var1 = c(1L, 3L, 1L), var2 = c(2L, 4L, 4L), Z = c(1.2, 
    5.4, 2.3)), .Names = c("var1", "var2", "Z"), row.names = c(NA, 
    3L), class = "data.frame")

您可以使用多种方法,包括:

矩阵索引

D <- max(unlist(mydf[1:2]))
M <- matrix(0, ncol = D, nrow = D)
M[as.matrix(mydf[1:2])] <- mydf[[3]]
M
#      [,1] [,2] [,3] [,4]
# [1,]    0  1.2    0  2.3
# [2,]    0  0.0    0  0.0
# [3,]    0  0.0    0  5.4
# [4,]    0  0.0    0  0.0

分解 "var1" 和 "var2" 并使用xtabs, spread, 或dcast

注意:以下所有答案均使用“var1”和“var2”已转换为factors 的数据集。

D <- max(unlist(mydf[1:2]))
mydf[1:2] <- lapply(mydf[1:2], factor, seq_len(D))
str(mydf)
# 'data.frame': 3 obs. of  3 variables:
#  $ var1: Factor w/ 4 levels "1","2","3","4": 1 3 1
#  $ var2: Factor w/ 4 levels "1","2","3","4": 2 4 4
#  $ Z   : num  1.2 5.4 2.3

xtabs(Z ~ var1 + var2, mydf)
#     var2
# var1   1   2   3   4
#    1 0.0 1.2 0.0 2.3
#    2 0.0 0.0 0.0 0.0
#    3 0.0 0.0 0.0 5.4
#    4 0.0 0.0 0.0 0.0

library(tidyr)
mydf %>% spread(var2, Z, fill = 0, drop = FALSE)
#   var1 1   2 3   4
# 1    1 0 1.2 0 2.3
# 2    2 0 0.0 0 0.0
# 3    3 0 0.0 0 5.4
# 4    4 0 0.0 0 0.0

library(data.table)
dcast(as.data.table(mydf), var1 ~ var2, value.var = "Z", fill = 0, drop = FALSE)
#    var1 1   2 3   4
# 1:    1 0 1.2 0 2.3
# 2:    2 0 0.0 0 0.0
# 3:    3 0 0.0 0 5.4
# 4:    4 0 0.0 0 0.0
于 2017-08-11T05:48:09.567 回答
0

其实我不熟悉R语言,但你可以使用我在java中完成的这种类型的逻辑..

int[] row1 = {1, 3, 1}; 
int[] row2 = {2, 4, 4};
double[] z = {1.2, 5.4, 2.3};

        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                for (int k = 0; k < row1.length; k++) {
                    if (row1[k] == i && row2[k] == j) {
                        System.out.println(z[k]);
                    }
                }
            }
            System.out.println("\n");
        }
于 2017-08-11T05:34:29.247 回答