在R

时间:2015-05-27 19:26:15

标签: r

对于示例数据框:

df1 <- structure(list(X = 1:15, a = c(2L, 3L, 4L, 3L, 7L, 5L, NA, 2L, 
9L, 7L, 0L, 1L, 20L, 15L, 14L)), .Names = c("X", "a"), 
   class = "data.frame", row.names = c(NA, 
-15L))

我使用以下代码将列'a'分成四分位数:

cut.at.n.tile <- function(X , n = 4){ 
  cut( X , breaks = quantile( X , 
     probs = (0:n)/n , na.rm = TRUE ) , include.lowest = TRUE )}
df1$a.quartile <- cut.at.n.tile( df1$a , n = 4)

如何用1 - 4(1为最低)替换标签?我不希望简单地重新编码这些值,因为我将使用不同的连续变量运行很多次。

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

labels参数用于cut ...

cut.at.n.tile <- function(X , n = 4){ 
   cut( X , breaks = quantile( X , 
      probs = (0:n)/n , na.rm = TRUE ) ,
      labels = 1:n,
      include.lowest = TRUE )}
cut.at.n.tile( df1$a , n = 4)
##  [1] 1    2    2    2    3    3    <NA> 1    4    3
##      1    1    4    4    4   
## Levels: 1 2 3 4

你可能也会对ggplot2::cut_number感兴趣 基本上是一样的......

ggplot2::cut_number(df1$a, n = 4, labels = 1:4)

答案 1 :(得分:1)

您也可以在剪切的fcn内将标签设置为FALSE;即

cut(df1$a,
    breaks = quantile( df1$a , 
                     probs = seq(0,1,.25) , na.rm = TRUE ),
    labels = F, # setting labels to false just makes labels integer codes instead of factor levels
    include.lowest = T)