Created
July 28, 2021 14:52
-
-
Save axjack/821b8035bd64f9e214c264edf5a95f02 to your computer and use it in GitHub Desktop.
tiny_R_script.R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
x <- c(100,100,100,200,200,300,300,300,400) | |
y <- rep( c('A','B','C'), 3 ) | |
z <- sample(1:9,9, replace = T) | |
df <- data.frame(x,y,z) | |
library(Matrix) | |
x1 <- factor(df$x) | |
y1 <- factor(df$y) | |
sparseMatrix( | |
i = as.integer(x1) | |
, j = as.integer(y1) | |
, x = df$z | |
, dims = c(length(levels(x1)), length(levels(y1)) ) | |
, dimnames = list(levels(x1),levels(y1)) | |
) -> sm1 | |
df %>% pivot_wider(names_from = x, values_from = z) -> sm2 | |
str(sm1) | |
str(sm2) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment