2016-08-13 22 views
0

重塑一个数据帧我有以下的数据帧:如何融化或保留所需的列

df <- structure(c("0.1620678925564", "-0.0609851972808482", "-0.101082695275552", 
"0.184268723991321", "-0.0899021067853178", "-0.0943666172060028", 
"-0.0531973808347148", "0.0213528550009522", "0.0318445258337625", 
"0.0179790366380429", "0.00347902775389391", "-0.0214580643919368", 
"-0.0760171167711921", "0.0344372228755224", "0.0415798938956697", 
"-0.114239469843063", "0.0217218301803764", "0.0925176396626868", 
"-0.0100499090500894", "0.0131491664210288", "-0.00309925737093941", 
"0.101206058442775", "0.0231964804556542", "-0.124402538898429", 
"0.0753224665976433", "-0.0323083061719772", "-0.0430141604256661", 
"-0.0654080281579984", "0.0124273486220488", "0.0529806795359496", 
"-0.0390251373720762", "-0.0115216989414941", "0.0505468363135703", 
"0.0321298528741327", "-0.0151866963239294", "-0.0169431565502034", 
"0.0288166559498562", "-0.0173984873138801", "-0.0114181686359761", 
"-0.0176892628883129", "-0.0235673738231865", "0.0412566367114994", 
"LAIV D0", "LAIV D3", "LAIV D7", "LAIV D0", "LAIV D3", "LAIV D7" 
), .Dim = c(6L, 8L), .Dimnames = list(c("1", "2", "3", "4", "5", 
"6"), c("Neutrophil", "Tcell", "Monocyte", "Bcell", "NKcell", 
"PlasmaCell", "DendriticCell", "samples"))) 

它看起来像这样:

Neutrophil   Tcell     Monocyte    Bcell     NKcell    PlasmaCell   
1 "0.1620678925564"  "-0.0531973808347148" "-0.0760171167711921" "-0.0100499090500894" "0.0753224665976433" "-0.0390251373720762" 
2 "-0.0609851972808482" "0.0213528550009522" "0.0344372228755224" "0.0131491664210288" "-0.0323083061719772" "-0.0115216989414941" 
3 "-0.101082695275552" "0.0318445258337625" "0.0415798938956697" "-0.00309925737093941" "-0.0430141604256661" "0.0505468363135703" 
4 "0.184268723991321" "0.0179790366380429" "-0.114239469843063" "0.101206058442775" "-0.0654080281579984" "0.0321298528741327" 
5 "-0.0899021067853178" "0.00347902775389391" "0.0217218301803764" "0.0231964804556542" "0.0124273486220488" "-0.0151866963239294" 
6 "-0.0943666172060028" "-0.0214580643919368" "0.0925176396626868" "-0.124402538898429" "0.0529806795359496" "-0.0169431565502034" 
    DendriticCell   samples 
1 "0.0288166559498562" "LAIV D0" 
2 "-0.0173984873138801" "LAIV D3" 
3 "-0.0114181686359761" "LAIV D7" 
4 "-0.0176892628883129" "LAIV D0" 
5 "-0.0235673738231865" "LAIV D3" 
6 "0.0412566367114994" "LAIV D7" 

我想要做的是融化它看起来像这样:

X1   X2    value 
1 'LAIV D0' Neutrophil  0.1620678925564 
2 'LAIV D3' Neutrophil -0.0609851972808482 
.... 

我该怎么做?

我试过但不会这样做。

library(reshape2) 
melt(df) 
+1

HTTP的可能欺骗:// stackoverflow.com/questions/2185252/reshaping-data-frame-from-宽到长格式 – Sumedh

回答

2

试试这个

df <- as.data.frame.matrix(df) 
melt(data = df,id.vars = c("samples")) 

将两个包reshapereshape2工作

2

我们还可以用gathertidyr

library(dplyr) 
library(tidyr) 
as.data.frame(df) %>% 
     gather(Var, Val, -samples)