aho*_*ltz 5 r matrix sparse-matrix tidyverse
我正在尝试从数据帧创建单位矩阵。数据框是这样的:
i<-c("South Korea", "South Korea", "France", "France","France")
j <-c("Rwanda", "France", "Rwanda", "South Korea","France")
distance <-c(10844.6822,9384,6003,9384,0)
dis_matrix<-data.frame(i,j,distance)
dis_matrix
1 South Korea South Korea 0.0000
2 South Korea Rwanda 10844.6822
3 South Korea France 9384.1793
4 France Rwanda 6003.3498
5 France South Korea 9384.1793
6 France France 0.0000
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个如下所示的矩阵:
South Korea France Rwanda
South Korea 0 9384.1793 10844.6822
France 9384.1793 0 6003.3498
Rwanda 10844.6822 6003.3498 0
Run Code Online (Sandbox Code Playgroud)
我尝试使用 Matrix 包中的 SparseMatrix,如此处所述(从数据帧创建稀疏矩阵)问题是 i 和 j 必须是整数,并且我有字符串。我无法找到另一个可以完成我正在寻找的功能。我将不胜感激任何帮助。谢谢
一个可能的解决方案:
\ntidyr::pivot_wider(dis_matrix, id_cols = i, names_from = j,\n values_from = distance, values_fill = 0)\n\n#> # A tibble: 2 \xc3\x97 4\n#> i Rwanda France `South Korea`\n#> <chr> <dbl> <dbl> <dbl>\n#> 1 South Korea 10845. 9384 0\n#> 2 France 6003 0 9384\nRun Code Online (Sandbox Code Playgroud)\n