【问题标题】:Using Hmisc cut2 arguments - how does the max argument work?使用 Hmisc cut2 参数 - max 参数如何工作?
【发布时间】:2020-05-22 00:37:07
【问题描述】:

我的庞大数据集中的长度不均匀。即 2016 年的 700 次观察,2017 年的 400 次观察。我有很多年的数据,因此手动裁剪数据集是不可行的。

我想将它们都切成分位数以进行观察,但每组只有前 400 个。=

Hmisc documentation 中有一个诱人的“minmax”参数。是否可以使用 minmax 作为参数,以便 Hmisc 仅从观测值 1-400 中删除分位数?

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。
  • minmax 参数对您没有帮助。对于那些错误指定削减的人来说,这只是一个安全网。

标签: r hmisc


【解决方案1】:

使用 dplyr,您可以使用 group_byslice 为每个年份值选择前 400 条记录。然后创建分位数,无论是在每年内还是整体上。

set.seed(911) # Simulate some uneven data
df <- data.frame(year=rep(2016:2018, times=c(400,500,600)),
                 val=rnorm(1500,50,5))

library(dplyr); library(tidyr)

这会在每年内创建分位数

df %>% group_by(year) %>%
  slice(1:400) %>%
  mutate(q4 = cut(val, 
                  breaks=quantile(val, 
                                  probs = seq(0,1,1/4)), 
                  include=TRUE, labels=FALSE)) %>%
# You can stop here and save the output, here I continue to check the counts
  count(q4) %>%
  pivot_wider(names_from=q4, values_from=n)
# A tibble: 3 x 5
# Groups:   year [3]
#   year   `1`   `2`   `3`   `4`
#  <int> <int> <int> <int> <int>
#1  2016   100   100   100   100
#2  2017   100   100   100   100
#3  2018   100   100   100   100

或者您可以取消分组以创建整体分位数(每年的计数会有所不同)。

df %>% group_by(year) %>%
  slice(1:400) %>%
  ungroup() %>%
  mutate(q4 = cut(val, 
                  breaks=quantile(val, 
                                  probs = seq(0,1,1/4)), 
                  include=TRUE, labels=FALSE)) %>% 
# Stop here to save, or continue to check the counts
  group_by(year) %>%
  count(q4) %>%
  pivot_wider(names_from=q4, values_from=n)

# A tibble: 3 x 5
# Groups:   year [3]
#   year   `1`   `2`   `3`   `4`
#  <int> <int> <int> <int> <int>
#1  2016   116    88   102    94
#2  2017    86   114    85   115
#3  2018    98    98   113    91

【讨论】:

  • 谢谢,爱德华!通常我在 MatLab 中处理所有数据并使用 R 来运行不寻常的模型或创建 GIS 图层。我希望能够在与数据相关的 R 中更成功地工作,您的详细解释非常有帮助,有助于推动我前进。
  • 哦 - 给任何读过这篇文章的人一个便条。 dpylr 也经常与包 tidyr 一起使用,在这种情况下,Edward 使用“pivot_wider”需要使用 tidyr,这里没有提到。但是,当使用“install.packages("tidyr")”安装 tidyr 时,会出现一个令人困惑的时刻,它会询问关于解包和安装的是否问题。点击“否”安装tidyr包,无需自己编译。
猜你喜欢
  • 1970-01-01
  • 2013-04-27
  • 1970-01-01
  • 1970-01-01
  • 2021-04-25
  • 2019-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多