How to create a daily numeric matrix from a data frame with x, y, date, and value columns.
I am trying to implement the SOM function from the Kohonen package in R for my data frame dtt. It requires a data matrix as input. So how can I convert dtt into daily matrix based on the x and y group so that I can implement SOM function? Sample data and code.
dtt <-structure(list(x = c(-175, -174, -176, -175, -174, -173, -177,
-176, -176, -175, -175, -174, -174, -173, -173, -178, -177, -176,
-175, -174, -173, -178, -177, -176, -175, -174, -173, -177, -176,
-175), y = c(55, 55, 54, 54, 54, 54, 53, 53, 53, 53, 53, 53,
53, 53, 53, 52, 52, 52, 52, 52, 52, 51, 51, 51, 51, 51, 51, 50,
50, 50), date = structure(c(9651, 9651, 9651, 9651, 9651, 9651,
9652, 9651, 9652, 9651, 9652, 9651, 9652, 9651, 9652, 9652, 9652,
9652, 9652, 9652, 9652, 9652, 9652, 9652, 9652, 9652, 9652, 9652,
9652, 9652), class = "Date"), value = c(316.613647460938, 316.79248046875,
317.312530517578, 318.800598144531, 318.795593261719, 317.331817626953,
317.249206542969, 317.226287841797, 320.043701171875, 318.493255615234,
321.331146240234, 318.14208984375, 321.068939208984, 316.213836669922,
319.203460693359, 316.927764892578, 320.787109375, 323.020355224609,
323.617523193359, 322.588897705078, 319.979583740234, 318.035278320312,
321.262054443359, 322.785919189453, 322.615661621094, 320.828125,
317.512573242188, 318.32177734375, 319.274078369141, 318.411285400391
)), row.names = c(NA, -30L), class = c("tbl_df", "tbl", "data.frame"
))
Unsuccesffulcode to convert into matrix.
dtt_mat <- dtt %>%
group_by(x, y)%>%
mutate(value = scale(value))%>%
unite("xy", c(x,y), sep = "_") %>%
tidyr::pivot_wider(names_from = xy, values_from = value)%>%
dplyr::select(-date) %>%
as.matrix()
dtt_mat
str(dtt_mat)
SOM implementation gives an error because the matrix dtt_mat is not proper
library(kohonen)
som_res <- som(X = dtt_mat,
grid = somgrid(xdim = 2, ydim = 2, topo = "rectangular"),
keep.data = T)
som_res
You may use
data.matrix().