Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 创建分位数_R_Matching_Quantile - Fatal编程技术网

R 创建分位数

R 创建分位数,r,matching,quantile,R,Matching,Quantile,我有一组个人的社会经济分数,从-6.3到3.5。现在,我想根据每个人的社会经济分数将他们分配到分位数 我有一个名为Healthdata的数据集,它有两列:Healthdata$SSE,和Healthdata$ID 最后,我想得到一个由SSE分位数匹配的数据帧 在R中如何做到这一点?这里有一种方法: # an example data set set.seed(1) Healthdata <- data.frame(SSE = rnorm(8), ID = gl(2, 4)) transf

我有一组个人的社会经济分数,从-6.3到3.5。现在,我想根据每个人的社会经济分数将他们分配到分位数

我有一个名为
Healthdata
的数据集,它有两列:
Healthdata$SSE
,和
Healthdata$ID

最后,我想得到一个由SSE分位数匹配的数据帧

在R中如何做到这一点?

这里有一种方法:

# an example data set
set.seed(1)
Healthdata <- data.frame(SSE = rnorm(8), ID = gl(2, 4))

transform(Healthdata, quint = ave(SSE, ID, FUN = function(x) {
  quintiles <- quantile(x, seq(0, 1, .2))
  cuts <- cut(x, quintiles, include.lowest = TRUE)
  quintVal <- quintiles[match(cuts, levels(cuts)) + 1]
  return(quintVal)
}))

#          SSE ID      quint
# 1 -0.6264538  1 -0.4644344
# 2  0.1836433  1  0.7482983
# 3 -0.8356286  1 -0.7101237
# 4  1.5952808  1  1.5952808
# 5  0.3295078  2  0.3610920
# 6 -0.8204684  2 -0.1304827
# 7  0.4874291  2  0.5877873
# 8  0.7383247  2  0.7383247
#示例数据集
种子(1)

Healthdata因此,让我们从基于您的描述的样本数据集开始:

set.seed(315)
Healthdata <- data.frame(SSE = sample(-6.3:3.5, 21, replace=TRUE), ID = gl(7, 3))
我知道你需要一个新的变量来识别个人社会经济地位的分位数组。我会这样做:

> Healthdata[1:15,]
    SSE ID
1  -0.3  1
2  -6.3  2
3  -1.3  3
4  -3.3  4
5  -5.3  5
6  -4.3  6
7  -4.3  7
8   0.7  8
9  -4.3  9
10 -4.3  10
11 -3.3  11
12  0.7  12
13 -2.3  13
14 -3.3  14
15  0.7  15
transform(Healthdata, Q = cut(Healthdata$SSE, 
                              breaks = quantile(Healthdata$SSE), 
                              labels = c(1, 2, 3, 4),
                              include.lowest=TRUE))
返回:

    SSE ID Q
1  -1.3  1 2
2  -6.3  2 1
3  -4.3  3 1
4   0.7  4 3
5   1.7  5 3
6   1.7  6 3
7  -5.3  7 1
8   1.7  8 3
9   2.7  9 4
10 -3.3 10 2
11 -1.3 11 2
12 -3.3 12 2
13  1.7 13 3
14  0.7 14 3
15 -4.3 15 1
如果要查看分位数范围的上限和下限,请省略
labels=c(1,2,3,4)
以返回此值:

    SSE ID           Q
1  -1.3  1 (-4.3,-1.3]
2  -6.3  2 [-6.3,-4.3]
3  -4.3  3 [-6.3,-4.3]
4   0.7  4  (-1.3,1.7]
5   1.7  5  (-1.3,1.7]

来自CreateQuintiles的搜索结果:(与“CreateDeciles”的结果类似。)非常感谢提供有用的资料。对R来说很陌生,学习也很慢。谢谢。这就是我要找的。另外,我尝试了gtools包,发现以下内容很有用。Q5=数量单位(SSE,q=seq(0,1,by=0.20))
    SSE ID           Q
1  -1.3  1 (-4.3,-1.3]
2  -6.3  2 [-6.3,-4.3]
3  -4.3  3 [-6.3,-4.3]
4   0.7  4  (-1.3,1.7]
5   1.7  5  (-1.3,1.7]