當你給表函數的一個因素,它使用係數的水平,建表。因此,通過在「FacilityName」的級別添加「Missing」可以獲得您想要的結果。
# loading data
ec <- read.csv(text=
'State, FacilityName, Date
NY,Loew,June 2014
NY,Loew,June 2014
CA,Sunrise,May 2014
CA,NA,May 2014',)
# Adding Missing to the possible levels of FacilityName
# note that we add it in front
new.levels <- c("Missing", levels(ec$FacilityName))
ec$FacilityName <- factor(ec$FacilityName, levels=new.levels)
# And replacing NAs by the new level "Missing"
ec$FacilityName[is.na(ec$FacilityName)] <- "Missing"
# the previous line would not have worked
# if we had not added "Missing" explicitly to the levels
# table() uses the levels to generate the table
# the levels are displayed in order
# now there's a level "Missing" in first position
t <- table(ec$FacilityName, ec$Date)
你得到:
> t
June 2014 May 2014
Missing 0 1
Loew 2 0
Sunrise 0 1
您可以添加這樣的行總(我不認爲有nrow
你的代碼你說什麼它)
# adding total line
rbind(t, TOTAL=colSums(as.matrix(t)))
June 2014 May 2014
Missing 0 1
Loew 2 0
Sunrise 0 1
TOTAL 2 2
在這一點你有一個矩陣,所以你可能想要傳遞給as.data.frame
。
如果你願意,這可以很容易地實現到一個單獨的功能。完全不需要綁定多個表:)
您能提供一個可重複的例子嗎? –
而你的問題是什麼都沒有返回?如果是這種情況,您需要在'volume'函數的最後一行使用'return(x)'。如果你的問題是在運行該函數後找不到'x',那麼你需要''將''x'分配給全局環境,這不是推薦的編碼習慣。另外,根據你的代碼,你所要做的並不需要函數。你正在編寫兩個沒有輸入的函數,只能用來濫用R的不合邏輯/後向範圍規則。 – Vlo
您沒有足夠的右括號 –