Home > Mobile >  How to convert data frame with x y z in long format to z matrix
How to convert data frame with x y z in long format to z matrix

Time:12-04

I have data frame df

x <- 1:10
y <- 1:10
df <- expand.grid(x = x, y = y)
df$z <- rnorm(100)

How to extract z as matrix z[x, y]?

I try to use pivot_wider

tidyr::pivot_wider(df, names_from = c(x, y), values_from = z)

but my syntax is wrong.

CodePudding user response:

Another solution is:

matrix(df$z, ncol=10, byrow=T)

            [,1]       [,2]       [,3]       [,4]         [,5]        [,6]         [,7]        [,8]        [,9]       [,10]
 [1,] -0.02407569 -0.6089898 -0.4665902  1.7703357  1.395931986 -0.86468970  1.807207155  0.42350582 -0.70457644  0.35833380
 [2,]  1.07957156 -0.2039980 -1.0873882  1.1723716  0.355398044 -0.61419301  0.438510714  0.07740619  0.30405937  1.00061069
 [3,]  0.04948764 -1.1627207 -0.9687359 -1.8921062  0.001345981  1.07070868  0.402150896 -1.12029910 -2.83447855 -0.45832572
 [4,]  1.52790476 -0.7563627 -1.2439350  0.3868697  0.718851937  0.77256476 -0.117232543 -0.00137484  0.56901789  1.52043160
 [5,]  1.35541143 -1.2450420 -1.5261489  0.8511285 -0.194413856  0.45793254 -1.706388785 -0.45600031  0.11765427 -0.01356355
 [6,] -0.23990926 -0.1667689 -0.9696469 -0.6323680 -1.532202133 -2.05989553  0.955730564 -1.72406365 -0.97206109  0.62405887
 [7,]  0.25976898  0.9236628  1.6037497  0.3995352  2.123141403 -0.08798201 -1.855792435 -0.87700338  0.47303724  0.62288576
 [8,]  0.01103355  0.4853405  0.7438026  0.3449940  0.177826612 -0.55062987 -0.967499466  1.18563042  0.19327203  0.43129302
 [9,] -1.78143079 -0.1857836  1.1055448 -1.1628949  0.816880205 -1.02522511  0.981808719 -1.48183636 -1.40054918  0.04793519
[10,] -1.54684218 -1.9361322 -1.5829184  2.1165249  0.858680415  0.24810084 -0.007996342 -0.16889899  0.06790111  0.63706385

CodePudding user response:

At least one name id column must be left over, just use one name in pivot_wider:

x <- 1:10
y <- 1:10
df <- expand.grid(x = x, y = y)
df$z <- rnorm(100)

df2 <- pivot_wider(df, names_from = x, values_from = z)
as.matrix(df2)

CodePudding user response:

I guess you could do:

    x <- 1:10
    y <- 1:10
    df <- expand.grid(x = x, y = y)
    df$z <- rnorm(100)
    
   df2<- do.call(rbind, lapply(split(df, df$x), function(d) `names<-`(d$z, d$y)))[,length(unique(df$x)):1]
    as.matrix(df2)

CodePudding user response:

The accepted answer works if (as in the example) the x and y coordinates are already both complete and ordered. For cases when the x and y coordinates are not complete (i.e., there are missing values), or not in the correct order, then we can do it like this:

m = matrix(nrow = length(y), ncol = length(x))
m[as.matrix(df[,c('y','x')])] = df[['z']]
  •  Tags:  
  • r
  • Related