Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将R中的矩阵数据帧与2个变量和1个值列融合?_R_Dataframe_Tidyr_Reshape2_Melt - Fatal编程技术网

如何将R中的矩阵数据帧与2个变量和1个值列融合?

如何将R中的矩阵数据帧与2个变量和1个值列融合?,r,dataframe,tidyr,reshape2,melt,R,Dataframe,Tidyr,Reshape2,Melt,我的数据如下所示: col1 col2 col3 col1 100 25 30 col2 25 200 50 col3 30 50 300 Var1 Var2 Value col1 col1 100 col1 col2 25 col1 col3 30 col2 col1 25 col2 col2 200 col2 col3 50 col3 col1 30 col3 col2 50 col3 col3 300 其中列和行名称为c(“col1”、“col2”、“col

我的数据如下所示:

    col1 col2 col3 
col1 100  25  30  
col2 25  200  50
col3 30  50   300
Var1 Var2 Value
col1 col1 100
col1 col2 25
col1 col3 30
col2 col1 25
col2 col2 200
col2 col3 50
col3 col1 30
col3 col2 50
col3 col3 300
其中列和行名称为c(“col1”、“col2”、“col3”)

我希望它看起来像这样:

    col1 col2 col3 
col1 100  25  30  
col2 25  200  50
col3 30  50   300
Var1 Var2 Value
col1 col1 100
col1 col2 25
col1 col3 30
col2 col1 25
col2 col2 200
col2 col3 50
col3 col1 30
col3 col2 50
col3 col3 300
我正在尝试重塑2::melt,但它没有给我想要的结果
melt(df)
,任何帮助都将不胜感激


谢谢。

在为
表创建属性之后,我们可以将
base R
as.data.frame
一起使用

as.data.frame.table(m1)
#   Var1 Var2 Freq
#1 col1 col1  100
#2 col2 col1   25
#3 col3 col1   30
#4 col1 col2   25
#5 col2 col2  200
#6 col3 col2   50
#7 col1 col3   30
#8 col2 col3   50
#9 col3 col3  300
数据
m1在为
表创建属性后,我们可以将
base R
as.data.frame
一起使用

as.data.frame.table(m1)
#   Var1 Var2 Freq
#1 col1 col1  100
#2 col2 col1   25
#3 col3 col1   30
#4 col1 col2   25
#5 col2 col2  200
#6 col3 col2   50
#7 col1 col3   30
#8 col2 col3   50
#9 col3 col3  300
数据
m1tidyr软件包就是您需要的

library(tidyr)

df <- gather(df, 'Var2', 'Value' 2:4)
library(tidyr)

dftidyr软件包就是您所需要的

library(tidyr)

df <- gather(df, 'Var2', 'Value' 2:4)
library(tidyr)
df