2015-07-10 22 views
0

我怎樣才能僞table()兩個變量,但填充第三列/單獨列表中的值?用另一列中的值填充僞表()

實施例:

library(ggplot2) # diamonds data 
data(diamonds) 
T.matrix <- with(diamonds, table(color, clarity)) 

產地:

 clarity 
color I1 SI2 SI1 VS2 VS1 VVS2 VVS1 IF 
    D 42 1370 2083 1697 705 553 252 73 
    E 102 1713 2426 2470 1281 991 656 158 
    F 143 1609 2131 2201 1364 975 734 385 
    G 150 1548 1976 2347 2148 1443 999 681 
    H 162 1563 2275 1643 1169 608 585 299 
    I 92 912 1424 1169 962 365 355 143 
    J 50 479 750 731 542 131 74 51 

我想與由清晰度彩色類似的表,除了與填充物= reference$value代替table()的計數

reference <- expand.grid(clarity = c("I1", "SI2", "SI1", "VS2", "VS1","VVS2", "VVS1", "IF"), 
         color = c("D", "E", "F", "G", "H", "I", "J")) 
reference$value <- 1:56 

所以:[D,I1]的值爲1,[SI1,D] = 2,[VS2,H] = 36等

+0

@jeremycg你可以建議其他功能? – emehex

回答

2

嘗試tapply

tapply(diamonds$price, list(diamonds$color, diamonds$clarity), mean) 

tapply由變量組列表需要你所需的變量,這組通過,然後應用的最後一個函數。表格輸出可能不是很有用,取決於您的期望用途。

如果你想在一個更可用格式的數據,你可能需要使用dplyr

library(dplyr) 

diamonds %>% group_by(clarity, color) %>% 
      summarise(mean(price)) 

編輯:這是一樣的!

tapply(reference$value, list(reference$color, reference$clarity), FUN = sum) 

你需要的樂趣或tapply崩潰輸出

+1

偉大的解決方案!也許你想通過將你的代碼行作爲't()'的參數來使用你的結果的轉置形式,以獲得與OP中相同的列和行排列。 – RHertel

相關問題