英文:
Turn deciles into variables
问题
我目前正在查看一些用于logit的数据。我的logit运行得很好,但是有人要求我将数据分成十分位并可能对其进行处理。为此,我想我需要将我创建的十分位转化为变量(例如,十分位1、十分位2...)。我的问题是,我如何将我创建的十分位转化为可以进行其他操作的变量?
我尝试过搜索,但只能找到如何使用quantile(x, probs = seq (0,1,1/10))函数以及使用dplyr将数据分成分位数,但我找不到如何将它们转化为有用的内容。
提前感谢!
英文:
I am currently looking at some data that I am using for a logit. I have the logit working just fine, however, I am being asked to break out the data into deciles and then potentially do things with those. To that end, I imagine I need to turn the deciles I create into variables (e.g., decile 1, decile 2...). My question is, how can I turn the deciles I create into variables that I can then do something with?
I've tried Googling but I can only get how to break things down into quantiles using quantile(x, probs = seq (0,1,1/10)) function and also using dplyr. I can get the deciles just fine, but I can't find anything on how to turn those into anything useful.
Thanks in advance!
答案1
得分: 1
ntile会给你大部分你想要的,但它会返回一个数值结果。
我了解你想在模型中将分位数作为一个分类变量使用,所以你可能想要创建一个因子变量。
library(tidyverse)
x <- runif(30)
xf <- x %>%
  ntile(10) %>%
  paste0("第", .) %>%
  as.factor() %>%
  reorder(parse_number(as.character(.)))
print(xf)
#>  [1] 第4  第3  第6  第9  第7  第5  第7  第10 第1  第3  第2  第4  第8  第10 第10 第9  
#> [17] 第6  第2  第6  第8  第5  第4  第9  第5  第8  第7  第2  第1  第1  第3 
#> attr(,"scores")
#>     第1     第10      第2      第3      第4      第5      第6      第7      第8      第9 
#>       1      10       2       3       4       5       6       7       8       9 
#> 10 Levels: 第1 第2 第3 第4 第5 第6 第7 第8 第9 第10
在2023-02-13使用 reprex v2.0.2创建
英文:
ntile will give you most of what you want, but it will return a numeric result.
I gather you would like to use the decile as a categorical variable in a model, so you might want to create a factor varaible instead.
library(tidyverse)
x <- runif(30)
xf <- x %>%
  ntile(10) %>%
  paste0("decile", .) %>%
  as.factor() %>%
  reorder(parse_number(as.character(.)))
print(xf)
#>  [1] decile4  decile3  decile6  decile9  decile7  decile5  decile7  decile10
#>  [9] decile1  decile3  decile2  decile4  decile8  decile10 decile10 decile9 
#> [17] decile6  decile2  decile6  decile8  decile5  decile4  decile9  decile5 
#> [25] decile8  decile7  decile2  decile1  decile1  decile3 
#> attr(,"scores")
#>  decile1 decile10  decile2  decile3  decile4  decile5  decile6  decile7 
#>        1       10        2        3        4        5        6        7 
#>  decile8  decile9 
#>        8        9 
#> 10 Levels: decile1 decile2 decile3 decile4 decile5 decile6 decile7 ... decile10
<sup>Created on 2023-02-13 with reprex v2.0.2</sup>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论