2014-01-12 81 views
0

一個數據幀我有這樣的data.frame:重塑與reshape2

habitat <- data.frame(
    proportion = c(0.053, 0.139, 0.050, 0.756, 0.001, 0.084, 0.000, 0.011, 0.005, 0.066, 0.810, 0.025), 
    habitat = c("Non-irrigated arable land", "Pastures", "Natural grasslands", "Intertidal flats", "Sea and ocean", "Non-irrigated arable land", "Pastures", "Natural grasslands", "Beaches, dunes, sands", "Salt marshes", "Intertidal flats", "Sea and ocean"), 
    zone = c(rep("dark", 5), rep("light", 7))) 

habitat 

    proportion     habitat zone 
1  0.053 Non-irrigated arable land dark 
2  0.139     Pastures dark 
3  0.050  Natural grasslands dark 
4  0.756   Intertidal flats dark 
5  0.001    Sea and ocean dark 
6  0.084 Non-irrigated arable land light 
7  0.000     Pastures light 
8  0.011  Natural grasslands light 
9  0.005  Beaches, dunes, sands light 
10  0.066    Salt marshes light 
11  0.810   Intertidal flats light 
12  0.025    Sea and ocean light 

我需要重塑看起來像這樣:

enter image description here

可以這樣用reshape2做了什麼?

回答

2

嘗試使用melt然後dcast

library(reshape2) 
dcast(melt(habitat), ...~habitat) 

下面是輸出的一部分:

zone variable Beaches, dunes, sands Intertidal flats Natural grasslands 
1 dark proportion     NA   0.756    0.050 
2 light proportion     0.005   0.810    0.011 

您可以通過使用一個簡單的subseting

dcast(melt(habitat), ...~habitat)[, -2] 
1

你可以擺脫的variablestats包中執行此操作GE(這是在默認情況下,當您啓動[R加載)使用xtabs ....

xtabs(proportion ~zone + habitat , data = habitat) 
#  habitat 
#zone Beaches, dunes, sands Intertidal flats Natural grasslands Non-irrigated arable land Pastures Salt marshes Sea and ocean 
# dark     0.000   0.756    0.050      0.053 0.139  0.000   0.001 
# light     0.005   0.810    0.011      0.084 0.000  0.066   0.025 

或者保留NA是你可以使用tapply()從`基本包...

tapply(habitat$proportion, list(habitat$zone, habitat$habitat) , sum , na.rm = FALSE) 
#  Beaches, dunes, sands Intertidal flats Natural grasslands Non-irrigated arable land Pastures Salt marshes Sea and ocean 
#dark      NA   0.756    0.050      0.053 0.139   NA   0.001 
#light     0.005   0.810    0.011      0.084 0.000  0.066   0.025