重新编码百分位数:函数而不是 for 循环

Recoding percentiles: function instead of for-loop

我无法在任何地方找到我的问题的答案,所以这里是:

我想知道如何使用数据帧中的变量名进行 for 循环。

for ( EACH VARIABLE in DATAFRAME){
    operation
    }

我试过不同品种的 i in names(df) 等等,都没有成功。

我想做的很简单。我想重新编码变量:上 Xth 百分位数 = 1,其余 = 0。我已经能够按如下方式执行此操作:

   j <- ntile (df$variable, 100)
   newdf$variable_percentile <-j
   newdf$variable_binomial <- 0
   newdf$variable_binomial[j>x] <-1 

我将不胜感激为此循环提供的帮助,或者更轻松地执行此操作的方法。也许有一个功能并应用?

您真诚的, 连

此代码由 Rob Wanders 提供给我

indicator <- function(variable, quantile) {
    return(.bincode(variable,breaks=c(0,quantile(variable,probs=quantile[[1]],max(variable)),include.lowest=TRUE)-1)
}

indicator(data,90) 现在会将最高的 10% 编码为 1,其余的编码为 0