2013-01-01 23 views
2

縱向數據集我有數據集:創建具有重塑

top100_repository_name month monthly_increase monthly_begin_at monthly_end_with 
Bukkit     2012-03 9     431     440 
Bukkit     2012-04 19     438     457 
Bukkit     2012-05 19     455     474 
CodeIgniter    2012-03 15     492     507 
CodeIgniter    2012-04 50     506     556 
CodeIgniter    2012-05 19     555     574 

我用下列R-代碼:

library(reshape) 
latent.growth.data <- read.csv(file = "LGC_data.csv", header = TRUE) 
melt(latent.growth.data, id = c("top100_repository_name", "month"), measured = c("monthly_end_with")) 
cast(latent.growth.data, top100_repository_name + month ~ monthly_end_with) 

,我想用來創建一個具有以下結構的數據集:

top100_repository_name 2012-03 2012-04 2012-05 
Bukkit     440  457  474 
CodeIgniter    507  556  574 

但是,當我運行我的代碼時,我得到以下輸出:

Using monthly_end_with as value column. Use the value argument to cast to override this choice 
Error in `[.data.frame`(data, , variables, drop = FALSE) : 
    undefined columns selected 

如何修改我的代碼以便生成所需的輸出?

+1

我敢肯定,我的編輯是正確的,但請覈實。 –

+0

你需要做一些事情:(i)將熔化物的結果保存到一個物體,例如'latent.growth.melt',然後按照下面的'latent.growth.melt'運行。如果使用更新的reshape2包(推薦),則使用dcast()而不是cast() - 最後一行應該是'dcast(latent.growth.melt,top100_repository_name〜month,value.var =「value 「)'。你可以看看爲什麼通過看'latent.growth.melt'。 – Dennis

回答

6

有人會很快與我確定的plyr解決方案,但這裏是使用reshape函數的基本解決方案。

test <- read.table(textConnection("top100_repository_name month monthly_increase monthly_begin_at monthly_end_with 
Bukkit     2012-03 9     431     440 
Bukkit     2012-04 19     438     457 
Bukkit     2012-05 19     455     474 
CodeIgniter    2012-03 15     492     507 
CodeIgniter    2012-04 50     506     556 
CodeIgniter    2012-05 19     555     574"),header=TRUE) 

重塑這個位置數據:

test2 <- reshape(
    test[c("top100_repository_name","month","monthly_end_with")], 
    idvar="top100_repository_name", 
    timevar="month", 
    direction="wide" 
) 

修復名

names(test2) <- gsub("monthly_end_with.","",names(test2)) 

它看起來像:

> test2 
    top100_repository_name 2012-03 2012-04 2012-05 
1     Bukkit  440  457  474 
4   CodeIgniter  507  556  574 
+0

+1,當其他人從「reshape2」跳到'dcast'時,我通常嘗試給出基本的R方法,但這次你強迫我......;) – A5C1D2H2I1M1N2O1R2T1

4

下面是基地R.用一個漂亮的直接方法xtabs()

xtabs(monthly_end_with ~ top100_repository_name + month, test) 
#      month 
# top100_repository_name 2012-03 2012-04 2012-05 
#   Bukkit   440  457  474 
#   CodeIgniter  507  556  574 

as.data.frame.matrix(
    xtabs(monthly_end_with ~ top100_repository_name + month, test)) 
#    2012-03 2012-04 2012-05 
# Bukkit   440  457  474 
# CodeIgniter  507  556  574 

或者,通過@thelatemail所示,有從中可以用作「reshape2」包氏dcast如下:

dcast(test, top100_repository_name ~ month, value.var="monthly_end_with") 
# top100_repository_name 2012-03 2012-04 2012-05 
# 1     Bukkit  440  457  474 
# 2   CodeIgniter  507  556  574 
+0

+1對於'xtabs' - 我總是忘記它。 – thelatemail