0
我的數據框看起來是這樣的:子集根據數據幀中的組位數
df
city year wealth
a 2001 1
a 2002 30
b 2001 2
b 2002 20
c 2001 3
c 2002 10
我在尋找一個簡單的方法基於相對城財富數據幀到子集只有每年中城市。所以我要像這樣的輸出:
top_third
city year wealth
a 2002 30
c 2001 3
mid_third
city year wealth
b 2001 2
b 2002 20
low_third
city year wealth
c 2002 10
a 2001 1
的方法,我一直想這個樣子的:
top_third <- subset(df, wealth > quantile(wealth, 0.66, na.rm = TRUE))
non_rich <- subset(df, wealth <=quantile(wealth, 0.66, na.rm = TRUE))
mid_third <- subset(non_rich, wealth > quantile(wealth, 0.5, na.rm = TRUE))
low_third <- subset(non_rich, wealth <=quantile(wealth, 0.5, na.rm = TRUE))
我用這種方法遇到的最大的問題是,我可以沒有找到一種方法來計算每年在內的分位數。有誰知道一個簡單的方法來做到這一點?
這是否幫助你得到了什麼你要?使用data.table包('library(data.table)')將'df'作爲data.table('setDT(df)')。你通過做'df [,等級:=等級(財富)/長度(財富),= =「年」]來定義財富等級。最後,你根據等級劃分結果。 'split(df [,!「rank」,with = F],df $ rank)' – jav