2013-05-20 39 views
0

我的數據幀是這樣的:整形和過濾數據幀中的R

Location Data   Value Value_kind 
A  species1  11   single 
A  species2  10   mean 
A  species3  8   single 
A  latitude  5.016 
A  longitude  47.716 
A  plot   1 
B  species1  8   single 
B  species2  9   single 
B  species3  7   mean 
B  latitude  3.203 
B  longitude  40.563   
B  plot   2 

我想過濾只有singlevalue_kinds和數據它重塑爲:

Location species1 species2 species3 latitude longitude 
A    11  -  8  5.016  47.716 
B    8  9  -  3.203  40.563 
+0

你有什麼嘗試?另外,請爲您的數據提供'dput'輸出。 – Roland

+0

我使用了重塑庫,但我沒有成功。 –

回答

3

假設這樣的數據:

Lines <- "Location Data   Value Value_kind 
A  species1  11   single 
A  species2  10   mean 
A  species3  8   single 
A  latitude  5.016 
A  longitude  47.716 
A  plot   1 
B  species1  8   single 
B  species2  9   single 
B  species3  7   mean 
B  latitude  3.203 
B  longitude  40.563   
B  plot   2 
" 
DF <- read.table(text = Lines, header = TRUE, fill = TRUE) 

試試這個:

library(reshape2) 

DF.single <- subset(DF, Value_kind == "single" | Data == "latitude" | Data == "longitude") 
dcast(DF.single, Location ~ Data, value.var = "Value") 

最後一行給出:

Location latitude longitude species1 species2 species3 
1  A 5.016 47.716  11  NA  8 
2  B 3.203 40.563  8  9  NA 
+0

感謝這很好,但現在我發現,對於相同的位置我有不同的情節,以便dcast使用數據長度來處理那。你知道我怎麼能解決這個問題嗎? –

+0

它不清楚關於'plot'的想要什麼。在問題底部添加一個示例數據集和解決方案。在輸入數據上使用'dput'使其具有可重現性。 –

+0

謝謝我解決了它。 –

1

假設你的真實數據看起來像您的樣本數據,即每個位置的行都是相同的順序並且都存在,您可以執行以下操作:

library(data.table) 
dt = data.table(df) 

dt[Value_kind == "mean", Value := NA][, 
    as.list(setattr(Value, 'names', Data)), by = Location] 
# Location species1 species2 species3 latitude longitude plot 
#1:  A  11  NA  8 5.016 47.716 1 
#2:  B  8  9  NA 3.203 40.563 2 

(使用as.character(Data)如果您使用的因素,而不是字符串)

+0

感謝您的回覆,但當我使用origianl數據集時出現錯誤。這裏是我得到的錯誤:「j不評估到每個組的列數相同」 –

+0

@Nima,這是因爲你的數據集顯然沒有所有「位置」的相同數據。說'物種2'缺少位置'D';如果你想使用'data.table'解決方案,你必須先修復你的數據 – eddi