2012-11-27 45 views
6

我用自帶的lme4數據集工作,並且正在努力學習如何運用reshape2把它從長並轉換爲寬[全碼處的結束崗位。重塑一個複雜的數據集從長到廣泛使用重鑄()

library(lme4) 
data("VerbAgg") # load the dataset 

數據集有9個變量; 「憤怒」,「性別」和「ID」不「項目」有所不同,而「RESP」, 「BTYPE」,「就地」,「模式」和「R2」做。

我已成功能夠將數據集從長期使用重塑()轉換爲寬幅:

wide <- reshape(VerbAgg, timevar=c("item"), 
      idvar=c("id", 'Gender', 'Anger'), dir="wide") 

其中產量在123個變量316個觀察,似乎正確轉化。但是,我沒有成功使用reshape/reshape2重現寬數據幀。

wide2 <- recast(VerbAgg, id + Gender + Anger ~ item + variable) 
Using Gender, item, resp, id, btype, situ, mode, r2 as id variables 
Error: Casting formula contains variables not found in molten data: Anger 

我可能不完全清楚recast如何定義id變量,但我很困惑,爲什麼它看不到「憤怒」。同樣,

wide3 <- recast(VerbAgg, id + Gender + Anger ~ item + variable, 
       id.var = c("id", "Gender", "Anger")) 
Error: Casting formula contains variables not found in molten data: item 

任何人都可以看到我在做什麼錯?我很樂意獲得對融化/演員的更好理解!

全碼:

## load the lme4 package 
library(lme4) 
data("VerbAgg") 
head(VerbAgg) 
names(VerbAgg) 

# Using base reshape() 
wide <- reshape(VerbAgg, timevar=c("item"), 
       idvar=c("id", 'Gender', 'Anger'), dir="wide") 

# Using recast 
library(reshape2) 
wide2 <- recast(VerbAgg, id + Gender + Anger ~ item + variable) 
wide3 <- recast(VerbAgg, id + Gender + Anger ~ item + variable, 
       id.var = c("id", "Gender", "Anger")) 

# Using melt/cast 
m <- melt(VerbAgg, id=c("id", "Gender", "Anger")) 
wide <- o cast(m,id+Gender+Anger~...) 
Aggregation requires fun.aggregate: length used as default 
# Yields a list object with a length of 8? 

m <- melt(VerbAgg, id=c("id", "Gender", "Anger"), measure.vars = c(4,6,7,8,9)) 
wide <- dcast(m, id ~ variable) 
# Yields a data frame object with 6 variables. 
+0

+1因爲你**愛**理解融化/鑄造 – agstudy

+1

廣泛產生316觀察26個變量??當我檢查昏暗(寬)我有316行和123列。 – agstudy

+4

「熔化」然後「鑄造」會更好 - 然後你就可以更容易地看到發生了什麼問題。 – hadley

回答

3

我認爲下面的代碼你想要做什麼。

library(lme4) 
data("VerbAgg") 

# Using base reshape() 
wide <- reshape(VerbAgg, timevar=c("item"), 
       idvar=c("id", 'Gender', 'Anger'), dir="wide") 
dim(wide) # 316 123 

# Using melt/cast 
require(reshape2) 
m1 <- melt(VerbAgg, id=c("id", "Gender", "Anger","item"), measure=c('resp','btype','situ','mode','r2')) 
wide4 <- dcast(m1,id+Gender+Anger~item+variable) 
dim(wide4) # 316 123 

R> wide[1:5,1:6] 
    Anger Gender id resp.S1WantCurse btype.S1WantCurse situ.S1WantCurse 
1 20  M 1    no    curse   other 
2 11  M 2    no    curse   other 
3 17  F 3   perhaps    curse   other 
4 21  F 4   perhaps    curse   other 
5 17  F 5   perhaps    curse   other 

R> wide4[1:5,1:6] 
    id Gender Anger S1WantCurse_resp S1WantCurse_btype S1WantCurse_situ 
1 1  M 20    no    curse   other 
2 2  M 11    no    curse   other 
3 3  F 17   perhaps    curse   other 
4 4  F 21   perhaps    curse   other 
5 5  F 17   perhaps    curse   other 
+0

謝謝!我沒有意識到項目應該包含在ID中。這看起來不錯,謝謝! –