在R中将data.frame显示为表或矩阵

时间:2011-11-09 06:18:32

标签: r

我想展示以下data.frame

df <- structure(list(Variety = structure(c(2L, 3L, 4L, 5L, 6L, 7L, 
1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 
3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L, 2L, 3L, 4L, 
5L, 6L, 7L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 1L), .Label = c("F2022", 
"F9917", "Hegari", "JS2002", "JS263", "PC1", "Sadabahar"), class = "factor"), 
Priming = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 
4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 
6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 1L), .Label = c("CaCl2", 
"Dry", "Hydro", "KCL", "KNO3", "NaCl", "Onfarm"), class = "factor"), 
Letters = structure(c(1L, 3L, 10L, 11L, 10L, 19L, 27L, 5L, 
28L, 11L, 18L, 20L, 9L, 1L, 22L, 14L, 30L, 26L, 24L, 3L, 
22L, 9L, 16L, 10L, 15L, 25L, 6L, 7L, 17L, 30L, 18L, 13L, 
20L, 27L, 19L, 29L, 23L, 2L, 8L, 12L, 6L, 31L, 8L, 22L, 4L, 
32L, 21L, 33L, 2L), .Label = c("a", "at", "bcd", "bclq", 
"bcq", "bd", "bds", "chlq", "ds", "e", "efg", "efgmnor", 
"efgnor", "efgnr", "efgr", "eg", "fgmnor", "fmnor", "hijkl", 
"hijkp", "hikl", "hklq", "ijkmp", "ijmop", "jmop", "mno", 
"mnop", "mnor", "su", "t", "uv", "v", "w"), class = "factor")), .Names = c("Variety", 
"Priming", "Letters"), row.names = c(NA, -49L), class = "data.frame")

作为Table或带有Ordered Variety名称的矩阵沿着行和Ordered Priming名称沿着列,并在R的表主体中显示Letter列。

我无法弄清楚如何做到这一点。任何帮助将受到高度赞赏。提前谢谢。

2 个答案:

答案 0 :(得分:3)

这应该这样做。

d <- d[order(d$Variety,d$Priming),]
dw <- reshape(data = d, idvar = 'Variety', timevar = 'Priming',  direction = 'wide')
dw

您可能想要编辑列名称。

names(dw) <- gsub('Letters.', '', names(dw), fixed = TRUE)

答案 1 :(得分:0)

简单的

library(reshape2)
acast(data=df, formula=Variety~Priming)



          CaCl2 Dry   Hydro KCL  KNO3   NaCl    Onfarm
F2022     at    mnop  a     hklq bds    hijkl   uv    
F9917     a     bcq   hklq  ds   fgmnor su      chlq  
Hegari    bcd   mnor  efgnr eg   t      ijkmp   hklq  
JS2002    e     efg   t     e    fmnor  at      bclq  
JS263     efg   fmnor mno   efgr efgnor chlq    v     
PC1       e     hijkp ijmop jmop hijkp  efgmnor hikl  
Sadabahar hijkl ds    bcd   bd   mnop   bd      w