简体   繁体   中英

Showing data.frame as table or matrix in R

I want to show the following 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")

as Table or matrix with Ordered Variety names along rows and Ordered Priming names along columns and showing Letter column in the main body of the table in R.

I could not figure out how to do this. Any help will be highly appreciated. Thanks in advance.

This should do it.

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

You might want to edit the column names.

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

Simple one

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     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM