我正試圖計算每人獨特水果的平均數量(我通常的練習數據)。這與這兩行代碼很好地工作:tapply - 創建NA?
with(df, tapply(fruit, names, FUN = function(x) length(unique(x))))->uniques
sum(uniques)/length(unique(df$names))
aggregate(df[,"fruit"], by=list(id=names), FUN = function(x) length(unique(x)))->d1
sum(d1$x)/length(unique(df$names))
我的問題是,當我在我的真實數據上使用代碼它不起作用。我的真實數據是處方數據,我想要每個人平均數量的獨特藥物。使用tapply代碼,它似乎創建了原始df中不存在的全新患者id。它也已經給出了1000的NA值。有我的ID列沒有缺失值並沒有在drug_code列要麼
with(dt3, tapply(drug_code, id, FUN = function(x) length(unique(x))))->uniques
head(uniques)
uniques
Patient HAI0000001 NA
Patient HAI0000003 NA
Patient HAI0000008 NA
Patient HAI0000010 NA
Patient HAI0000014 NA
Patient HAI0000020 NA
table(dt3$id=="Patient HAI0000001") ##checking to see if HA10000001 occurs in original df. the dim of df are 228954 rows and 5 cols
FALSE
228954
對於聚集代碼我得到一個錯誤:
aggregate(dt3[,"drug_code"], by=list(id=id), FUN = function(x) length(unique(x)))->d1
Error in aggregate.data.frame(as.data.frame(x), ...) :
arguments must have same length
我不明白髮生了什麼。我的真實數據與我的練習數據相似,因爲它有一個ID欄,並有一個藥物/水果欄。 df中沒有丟失的數據。我知道lapply對數據框更好,但我不一定需要df。在任何情況下,tapply代碼都是針對df的練習數據。有沒有人知道這裏發生了什麼?
實踐DF:真實數據的
names<-as.character(c("john", "john", "john", "john", "john", "mary", "mary","mary","mary","mary", "jim", "sylvia","ted","ted","mary", "sylvia", "jim", "ted", "john", "ted"))
dates<-as.Date(c("2010-07-01", "2010-09-01", "2010-11-01", "2010-12-01", "2011-01-01", "2010-08-12", "2010-11-11", "2010-05-12", "2010-12-03", "2010-07-12", "2010-12-21", "2010-02-18", "2010-10-29", "2010-08-13", "2010-11-11", "2010-05-12", "2010-04-01", "2010-05-06", "2010-09-28", "2010-11-28"))
fruit<-as.character(c("kiwi","apple","banana","orange","apple","orange","apple","orange", "apple", "apple", "pineapple", "peach", "nectarine", "grape", "melon", "apricot", "plum", "lychee", "watermelon", "apple"))
df<-data.frame(names,dates,fruit)
例如:
head(dt3)
id quantity date_of_claim drug_code index
1 Patient HAI0000560 1 2009-10-15 R03AC02 2010-04-06
2 Patient HAI0000560 1 2009-10-15 R03AK06 2010-04-06
3 Patient HAI0000560 30 2009-10-15 R03BB04 2010-04-06
4 Patient HAI0000560 30 2009-10-15 A02BC01 2010-04-06
5 Patient HAI0000560 50 2009-10-15 M02AA15 2010-04-06
6 Patient HAI0000560 30 2009-10-15 N02BE51 2010-04-06
嗨Dwin,謝謝你的迴應。拖尾空間在我轉移代碼時只是一個錯誤,這不是問題的原因。使用平均函數比我所做的要好 - 但這不是問題。問題是挑戰。它創造了所有這些不應該是的Nas。它在虛擬數據上工作正常,我無法弄清楚它爲什麼不能在真實數據上工作。 dummydata等於實際數據,因爲tapply代碼中的所有變量都是因子變量。在真實數據中沒有Nas開始,所以我不知道爲什麼tapply在製作它們。 – user2363642
堅持 - 想想我已經想出了一些 - - 敬請關注 – user2363642
如果您想發佈'dput(head(dt3))',我們可以提供更好的幫助。 –