R - convert data.frame to multi-dimensional matrix

前端 未结 3 1713
终归单人心
终归单人心 2021-01-28 03:30

From example from a data.frame:

x = data.frame(c(1,1,2,2,3,3), c(1,2,1,2,1,2), c(1,1,1,2,2,2), c(12,14,22,24,34,28))
colnames(x)=c(\"Store\",\"Dept\",\"Year\",\"         


        
相关标签:
3条回答
  • 2021-01-28 03:56

    Something like :

    tapply(X = x[["Sales"]], INDEX = x[setdiff(names(x), "Sales")], FUN = identity)
    

    could work, but it is a bit strange to use tapply with the identity function.

    0 讨论(0)
  • 2021-01-28 04:02

    Are you, perhaps, looking for xtabs?

    xtabs(Sales ~ Store + Dept + Year, x)
    # , , Year = 1
    # 
    #      Dept
    # Store  1  2
    #     1 12 14
    #     2 22  0
    #     3  0  0
    # 
    # , , Year = 2
    # 
    #      Dept
    # Store  1  2
    #     1  0  0
    #     2  0 24
    #     3 34 28
    
    0 讨论(0)
  • 2021-01-28 04:11

    You have to construct the array before with the appropriate dimension :

    Sales <- array(NA, c(max(x$Store), max(x$Dept), max(x$Year)))
    

    and then fill in the data :

    for (i in 1:nrow(x)) 
        Sales[x[i,"Store"], x[i,"Dept"], x[i,"Year"]] <- x[i, "Sales"]
    
    Sales[35,71,1]
    
    0 讨论(0)
提交回复
热议问题