问题描述
我想使用包含复杂调查样本设计的另一列(连续变量)的分位数来计算新列.这个想法是在数据框中创建一个新变量,指示每个观察值属于哪个分位数组
I want to compute a new column using the quantiles of another column (a continuous variable) incorporating the Sample Design of a complex survey. The idea is to create in the the data frame a new variable that indicates which quantile group each observation falls into
以下是我在不包含示例设计的情况下执行想法的方式,因此您可以了解我的目标.
Here is how I execute the idea without incorporating the sample design, so you can understand what I'm aiming for.
# Load Data
data(api)
# Convert data to data.table format (mostly to increase speed of the process)
apiclus1 <- as.data.table(apiclus1)
# Create deciles variable
apiclus1[, decile:=cut(api00,
breaks=quantile(api00,
probs=seq(0, 1, by=0.1), na.rm=T),
include.lowest= TRUE, labels=1:10)]
我已经尝试使用 survey
包中的 svyquantile
,但我无法解决这个问题.此代码不会将分位数组作为输出返回,我可以将其输入到新变量中.对此有什么想法吗?
I've tried using svyquantile
from the survey
package, but I couldn't get my head around this problem. This code does not return the quantile groups as an output that I can feed into a new variable. Any thoughts on this?
# Load Package
library(survey)
# create survey design
dclus1 <- svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
# What I've tried to do
svyquantile(~api00, design = dclus1, quantiles = seq(0, 1, by=0.1), method = "linear", ties="rounded")
推荐答案
library(survey)
data(api)
dclus1 <- svydesign(id=~dnum, weights=~pw, data=apiclus1, fpc=~fpc)
a <- svyquantile(~api00, design = dclus1, quantiles = seq(0, 1, by=0.1), method = "linear", ties="rounded")
# use factor() and findInterval()
dclus1 <- update( dclus1 , qtile = factor( findInterval( api00 , a ) ) )
# distribution
svymean( ~ qtile , dclus1 )
# or without the one observation in group number 11
dclus1 <- update( dclus1 , qtile = factor( findInterval( api00 , a[ -length( a ) ] ) ) )
# distribution
svymean( ~ qtile , dclus1 )
# quantiles by group
b <- svyby(~api00, ~stype, design = dclus1, svyquantile, quantiles = seq(0, 0.9 , by=0.1) ,ci=T)
# copy over your data
x <- apiclus1
# stype of each record
match( x$stype , b$stype )
# create the new qtile variable
x$qtile_by_stype <- factor( diag( apply( data.frame( b )[ match( x$stype , b$stype ) , 2:11 ] , 1 , function( v , w ) findInterval( w , v ) , x$api00 ) ) )
# re-create the survey design
dclus1 <- svydesign(id=~dnum, weights=~pw, data=x, fpc=~fpc)
# confirm you have quantiles
svyby( ~ qtile_by_stype , ~ stype , dclus1 , svymean )
这篇关于计算包含样本设计的分位数(调查包)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!