【问题标题】:R Quantile Error - replacement has n rows, data has pR 分位数错误 - 替换有 n 行,数据有 p
【发布时间】:2017-09-19 04:36:00
【问题描述】:

我正在尝试根据前 30 个百分位数、中间 40 个百分位数和底部 30 个百分位数创建对某个变量(在代码中称为 wt_avg)进行分类。

例如——

structure(list(x = 1:10, class = c(1, 1, 1, 2, 2, 2, 2, 3, 3, 
3)), .Names = c("x", "class"), row.names = c(NA, -10L), class = "data.frame")

其中“x”是数据,“类”是我想要的输出。

这是我正在使用的代码 -

sent_data$wt_avg = with(sent_data, SENT_Orth_1 + SENT_Orth_2 + SENT_Orth_3)
sent_data$state = quantile(sent_data$wt_avg, probs = c(0, 0.3, 0.7, 1) 
           na.rm = TRUE)

我收到以下错误 -

$<-.data.frame(*tmp*, "state", value = c(-13.38, -2.9725, 中的错误:替换有 5 行,数据有 603 行

我该如何解决这个问题?谢谢!

【问题讨论】:

  • quantile 的输出略有不同。它返回长度与初始向量不同的输出,即quantile(1:10, c(0, 0.3, 0.7, 1))# 0% 30% 70% 100% 1.0 3.7 7.3 10.0 您可以将其存储为汇总数据集而不是新列
  • 啊,好吧!然后我必须使用“if”条件来实际创建“状态”变量进行分类?有没有更快的方法?谢谢!
  • 很抱歉没有添加可重现的示例和预期的输出。我现在已经编辑了我的问题。
  • 我在下面发布了一个解决方案

标签: r quantile


【解决方案1】:

我们可以在cutfindInterval 中使用quantile

sent_data$newclass <- with(sent_data, findInterval(x, quantile(x,
         probs = c(0, 0.3, 0.7, 1)), rightmost.closed = TRUE))
sent_data
#    x class newclass
#1   1     1        1
#2   2     1        1
#3   3     1        1
#4   4     2        2
#5   5     2        2
#6   6     2        2
#7   7     2        2
#8   8     3        3
#9   9     3        3
#10 10     3        3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 2018-04-10
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多