Home > Mobile >  Creating a column out of quartiles from another column
Creating a column out of quartiles from another column

Time:01-04

I want to make a new column out of quartiles from another column

df <- within(df, quartile <- as.integer(cut(df$x, quantile(df$x, probs=0:4/4), include.lowest=TRUE)))

When I use this code I get

Error in `[<-.data.frame`(`*tmp*`, del, value = NULL) :    missing values are not allowed in subscripted assignments of data frames

df$x is numeric and doesn't have any NAs.

> sum(is.na(df$x))
[1] 0

Although in my df there are some NAs in some columns, I do not use those columns in the function mentioned above. I can't figure out where the problem is.


This function actually works.

df$Quartile <-cut(df$x,quantile(df$x),include.lowest=TRUE,labels=FALSE)

But the assigned variable df$Quartile doesn't appear in the dataframe.

CodePudding user response:

I would just use dplyr::mutate to add a new column.

library(dplyr)
df = df %>% 
    mutate(q_col = cut(x, quantile(x), include.lowest=TRUE, labels=FALSE))
                     mpg cyl  disp  hp drat    wt  qsec vs am gear carb q_col
Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4     3
Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4     3
Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1     3
Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1     3
Hornet Sportabout   18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2     2
Valiant             18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1     2
Duster 360          14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4     1
  •  Tags:  
  • Related