2011-08-26 73 views
5

假設我想從頭開始生成大型數據框。創建大型數據框

使用data.frame函數是我通常如何創建數據框。 但是,df類似以下內容極易出錯且效率低下。

那麼有沒有更有效的方式來創建下面的數據框。

df <- data.frame(GOOGLE_CAMPAIGN=c(rep("Google - Medicare - US", 928), rep("MedicareBranded", 2983), 
            rep("Medigap", 805), rep("Medigap Branded", 1914), 
            rep("Medicare Typos", 1353), rep("Medigap Typos", 635), 
            rep("Phone - MedicareGeneral", 585), 
            rep("Phone - MedicareBranded", 2967), 
            rep("Phone-Medigap", 812), 
            rep("Auto Broad Match", 27), 
            rep("Auto Exact Match", 80), 
            rep("Auto Exact Match", 875)),     
       GOOGLE_AD_GROUP=c(rep("Medicare", 928), rep("MedicareBranded", 2983), 
            rep("Medigap", 805), rep("Medigap Branded", 1914), 
            rep("Medicare Typos", 1353), rep("Medigap Typos", 635), 
            rep("Phone ads 1-Medicare Terms",585), 
            rep("Ad Group #1", 2967), rep("Medigap-phone", 812), 
            rep("Auto Insurance", 27), 
            rep("Auto General", 80), 
            rep("Auto Brand", 875))) 

哎呀,那是一些'壞'的代碼。如何以更高效的方式生成這個「大型」數據框?

+0

我很喜歡c好歹你爲什麼在這兩列中都有這麼多重複的數據。通常,當我在一列中重複數據時,它會在另一列中變化或循環(以二進制計算)。 – Owen

回答

7

如果你對這些信息的唯一來源是一張紙,那麼你可能不會得到太多比這更好的,但你至少可以整合所有到一個單一的rep呼籲每一列:

#I'm going to cheat and not type out all those strings by hand 
x <- unique(df[,1]) 
y <- unique(df[,2]) 

#Vectors of the number of times for each  
x1 <- c(928,2983,805,1914,1353,635,585,2967,812,27,955) 
y1 <- c(x1[-11],80,875) 

dd <- data.frame(GOOGLE_CAMPAIGN = rep(x, times = x1), 
       GOOGLE_AD_GROUP = rep(y, times = y1)) 

這應該是相同的:

> all.equal(dd,df) 
[1] TRUE 

但是,如果這個信息已經在R中的數據結構在某種程度上,你只需要變換它可能會更容易,但我們需要知道那個結構是什麼。

+0

該死的..再次擊敗我...... – John

+0

@John對不起。我已經丟失了我丟棄的答案的數量,因爲有人毆打我,如果這讓你感覺更好。 – joran

+0

它不......你可以給我發送一百萬美元......這將有助於 – John

3

手動,(1)創建該數據幀:

> dfu <- unique(df) 
> rownames(dfu) <- NULL 
> dfu 
      GOOGLE_CAMPAIGN   GOOGLE_AD_GROUP 
1 Google - Medicare - US     Medicare 
2   MedicareBranded   MedicareBranded 
3     Medigap     Medigap 
4   Medigap Branded   Medigap Branded 
5   Medicare Typos    Medicare Typos 
6   Medigap Typos    Medigap Typos 
7 Phone - MedicareGeneral Phone ads 1-Medicare Terms 
8 Phone - MedicareBranded    Ad Group #1 
9   Phone-Medigap    Medigap-phone 
10  Auto Broad Match    Auto Insurance 
11  Auto Exact Match    Auto General 
12  Auto Exact Match     Auto Brand 

和(2)的長度的這種載體:

> lens <- rle(as.numeric(interaction(df[[1]], df[[2]])))$lengths 
> lens 
[1] 928 2983 805 1914 1353 635 585 2967 812 27 80 875 

從這兩個輸入(dfulens),我們可以重建df (這裏叫做df2):

> df2 <- dfu[rep(seq_along(lens), lens), ] 
> rownames(df2) <- NULL 
> identical(df, df2) 
[1] TRUE