Skip to Content

crosstab and xtabs generates zeros instead of NAs

I have used the following (sample) data and crosstab() to create a cross-table dataset. When I use this method all the column x row combinations without data becomes zeros in my output dataset. I would like them to be NAs as there are true zero values in the dataset and I cannot distinguish them otherwise.Additionally, I have experimented with xtabs() and get the same problem. Any suggestions for getting the NAs or another method is very much appreciated.

WW1_Data <- structure(list(Site_Name = c("Alnön", "Alnön", "Alnön", "Ammarnäs",
"Ammarnäs", "Anjan", "Anjan", "Bäcksand", "Bäcksand", "Fittjebodarna",
"Fittjebodarna", "Flatruet", "Flatruet", "Flatruet", "Flatruet",
"Glen", "Glen", "Glen", "Idre", "Idre"), Year = c("1996", "2000",
"2010", "1996", "2011", "2009", "2010", "2000", "2010", "2008",
"2009", "2008", "2009", "2010", "2011", "2008", "2009", "2010",
"1996", "2010"), WW1_Pct_2 = c(0.307692307692308, 0.260869565217391,
0.0833333333333333, 0.75, 0.8, 0.52, 0.5, 0.0833333333333333,
0.375, 0.4, 0.423076923076923, 0.85, 0.483870967741935, 0.56,
0.58, 0.777777777777778, 0.555555555555556, 0.521739130434783,
0.4, 0)), .Names = c("Site_Name", "Year", "WW1_Pct_2"), row.names = c(3L,
4L, 5L, 8L, 9L, 10L, 11L, 15L, 16L, 28L, 29L, 30L, 31L, 32L,
33L, 42L, 43L, 44L, 59L, 60L), class = "data.frame")
 
xtabs(WW1_Pct_2 ~ Site_Name + Year, WW1_Data)
 
## alternatively ##
 
library(ecodist)
WW1_XTAB  <- data.frame(with(WW1_Data, crosstab(Site_Name, Year, WW1_Pct_2)))