将十分位数转化为变量

huangapple go评论91阅读模式
英文:

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会给你大部分你想要的,但它会返回一个数值结果。

我了解你想在模型中将分位数作为一个分类变量使用,所以你可能想要创建一个因子变量。

  1. library(tidyverse)
  2. x <- runif(30)
  3. xf <- x %>%
  4. ntile(10) %>%
  5. paste0("第", .) %>%
  6. as.factor() %>%
  7. reorder(parse_number(as.character(.)))
  8. print(xf)
  9. #> [1] 第4 第3 第6 第9 第7 第5 第7 第10 第1 第3 第2 第4 第8 第10 第10 第9
  10. #> [17] 第6 第2 第6 第8 第5 第4 第9 第5 第8 第7 第2 第1 第1 第3
  11. #> attr(,"scores")
  12. #> 第1 第10 第2 第3 第4 第5 第6 第7 第8 第9
  13. #> 1 10 2 3 4 5 6 7 8 9
  14. #> 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.

  1. library(tidyverse)
  2. x &lt;- runif(30)
  3. xf &lt;- x %&gt;%
  4. ntile(10) %&gt;%
  5. paste0(&quot;decile&quot;, .) %&gt;%
  6. as.factor() %&gt;%
  7. reorder(parse_number(as.character(.)))
  8. print(xf)
  9. #&gt; [1] decile4 decile3 decile6 decile9 decile7 decile5 decile7 decile10
  10. #&gt; [9] decile1 decile3 decile2 decile4 decile8 decile10 decile10 decile9
  11. #&gt; [17] decile6 decile2 decile6 decile8 decile5 decile4 decile9 decile5
  12. #&gt; [25] decile8 decile7 decile2 decile1 decile1 decile3
  13. #&gt; attr(,&quot;scores&quot;)
  14. #&gt; decile1 decile10 decile2 decile3 decile4 decile5 decile6 decile7
  15. #&gt; 1 10 2 3 4 5 6 7
  16. #&gt; decile8 decile9
  17. #&gt; 8 9
  18. #&gt; 10 Levels: decile1 decile2 decile3 decile4 decile5 decile6 decile7 ... decile10

<sup>Created on 2023-02-13 with reprex v2.0.2</sup>

huangapple
  • 本文由 发表于 2023年2月13日 23:26:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75437906.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定