Problem
I have a simple matrix:
library(tidyverse)
m <- matrix(seq(1,25), nrow = 5, ncol =5)
m
#> [,1] [,2] [,3] [,4] [,5]
#> [1,] 1 6 11 16 21
#> [2,] 2 7 12 17 22
#> [3,] 3 8 13 18 23
#> [4,] 4 9 14 19 24
#> [5,] 5 10 15 20 25
This matrix contains values, that I would like to store as a third column in a dataframe that contains all combinations of indices:
library(tidyverse)
df <- expand_grid(V1 = 1:5, V2 = 1:5)
Attempt
df <- df %>%
mutate(value = m[V1, V2])
This stores an entire matrix per dataframe field and not only the corresponding value.
Expected output
#> # A tibble: 25 x 3
#> V1 V2 value
#> <int> <int> <int>
#> 1 1 1 1
#> 2 1 2 6
#> 3 1 3 11
#> 4 1 4 16
#> and so on...
Question
How do I do this with mutate in R?
Note
I know that in this case, I could just reshape the data. However, I would like to apply the same approach to a multidimensional array (i.e., mutate(value = m[V1,V2,V3])
, that does contain only a subset of index combinations. Hopefully, the question is clear, otherwise: let me know:)!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…