R 分位数错误 - 替换有 n 行,数据有 p

R Quantile Error - replacement has n rows, data has p

我正在尝试根据前 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" 是数据,"class" 是我想要的输出。

这是我正在使用的代码 -

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

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

我们可以在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