R中的变换矩阵
我目前面临将矩阵转换为以下格式的问题。如何以最简单的方式在R中实现这一点?理想情况下,我希望使用第二个矩阵作为数据帧。非常感谢R中的变换矩阵,r,dataframe,matrix,tidyverse,data-transform,R,Dataframe,Matrix,Tidyverse,Data Transform,我目前面临将矩阵转换为以下格式的问题。如何以最简单的方式在R中实现这一点?理想情况下,我希望使用第二个矩阵作为数据帧。非常感谢 Estonia Germany Poland Estonia 0 2 3 Germany 2 0 4 Poland 3 4 0 Country1 Country2 Weight Estonia Estonia 0 Estonia
Estonia Germany Poland
Estonia 0 2 3
Germany 2 0 4
Poland 3 4 0
Country1 Country2 Weight
Estonia Estonia 0
Estonia Germany 2
Estonia Poland 3
Germany Estonia 2
...
如果矩阵称为mat,则可以使用:
library(tibble)
library(tidyr)
mat %>%
as.data.frame() %>%
rownames_to_column('Country1') %>%
pivot_longer(cols = -Country1, names_to = 'Country2', values_to = 'Weight')
# Country1 Country2 Weight
# <chr> <chr> <int>
#1 Estonia Estonia 0
#2 Estonia Germany 2
#3 Estonia Poland 3
#4 Germany Estonia 2
#5 Germany Germany 0
#6 Germany Poland 4
#7 Poland Estonia 3
#8 Poland Germany 4
#9 Poland Poland 0
资料
如果矩阵称为mat,则可以使用:
library(tibble)
library(tidyr)
mat %>%
as.data.frame() %>%
rownames_to_column('Country1') %>%
pivot_longer(cols = -Country1, names_to = 'Country2', values_to = 'Weight')
# Country1 Country2 Weight
# <chr> <chr> <int>
#1 Estonia Estonia 0
#2 Estonia Germany 2
#3 Estonia Poland 3
#4 Germany Estonia 2
#5 Germany Germany 0
#6 Germany Poland 4
#7 Poland Estonia 3
#8 Poland Germany 4
#9 Poland Poland 0
资料
另一种非整洁的方式:
df <- as.data.frame(as.table(mat))
names(df) <- c("Country1", "Country2", "Weight")
df
# Country1 Country2 Weight
# 1 Estonia Estonia 0
# 2 Germany Estonia 2
# 3 Poland Estonia 3
# 4 Estonia Germany 2
# 5 Germany Germany 0
# 6 Poland Germany 4
# 7 Estonia Poland 3
# 8 Germany Poland 4
# 9 Poland Poland 0
另一种非整洁的方式:
df <- as.data.frame(as.table(mat))
names(df) <- c("Country1", "Country2", "Weight")
df
# Country1 Country2 Weight
# 1 Estonia Estonia 0
# 2 Germany Estonia 2
# 3 Poland Estonia 3
# 4 Estonia Germany 2
# 5 Germany Germany 0
# 6 Poland Germany 4
# 7 Estonia Poland 3
# 8 Germany Poland 4
# 9 Poland Poland 0
我们可以用熔化剂
数据
我们可以用熔化剂
数据
另一个基本R选项
> cbind(expand.grid(dimnames(mat)), Weight = c(mat))
Var1 Var2 Weight
1 Estonia Estonia 0
2 Germany Estonia 2
3 Poland Estonia 3
4 Estonia Germany 2
5 Germany Germany 0
6 Poland Germany 4
7 Estonia Poland 3
8 Germany Poland 4
9 Poland Poland 0
另一个基本R选项
> cbind(expand.grid(dimnames(mat)), Weight = c(mat))
Var1 Var2 Weight
1 Estonia Estonia 0
2 Germany Estonia 2
3 Poland Estonia 3
4 Estonia Germany 2
5 Germany Germany 0
6 Poland Germany 4
7 Estonia Poland 3
8 Germany Poland 4
9 Poland Poland 0
这太酷了!这太酷了!