嵌套'ifelse' - 分位数的陈述 [英] Nested 'ifelse'-statement for quantiles

查看:114
本文介绍了嵌套'ifelse' - 分位数的陈述的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图根据数据框中的分位数将1到10之间的数字分配给一系列向量。

I am attempting to assign a number from 1 through 10 to a series of vectors based on what quantile they're in in a dataframe.

到目前为止我有试过

quants <- quantile(Data$Avg, c(.1, .2, .3, .4, .5, .6, .7, .8, .9)) 

Data$quant <- for ( i in nrow(Data) ) {
  ifelse(Data$Avg [i] < quants[1], Data$quant[1] = 1 , 
         ifelse(Data$Avg [i] > quants[1] & Data$Avg[i] < quants[2], Data$quant[1] = 2, Data$quant = 3
                   ))}

我收到以下错误:

< img src =https://i.stack.imgur.com/VQZrS.pngalt =在此处输入图像说明>

任何人都可以发现我在这里犯的错误?

Can anyone spot the mistake I am making here?

推荐答案

你可能最好使用 cut 而不是循环:

You might be better off using cut rather than a loop:

Data = data.frame(Avg = runif(100))
quantpoints <- seq(0.1, 0.9, 0.1)
quants <- quantile(Data$Avg, quantpoints)

cutpoints <- c(-Inf, quants, Inf)

cut(Data$Avg, breaks = cutpoints, labels = seq(1, length(cutpoints) - 1))

这篇关于嵌套'ifelse' - 分位数的陈述的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆