Search code examples
rcategorization

Error of unexpected ')' when using cut() function


so I'm trying to use the cut function to make a numeric variable into a categorical variable, and I keep getting an error of unexpected characters, but have triple checked my spelling so not sure what is wrong, can anyone help? this is the code:

[ca_timechcare_categorical:= cut(ca_timechcare, break=c(0,36,72,108,Inf),

include.lowest=TRUE,

labels=c("Very_Low", "Low", "High", "Very_High"))]

dataset[,table(ca_timechcare_categorical)]

and this is the error I'm receiving:

Error: unexpected ')' in "labels=c("Very_Low", "Low", "High", "Very_High"))"

Thanks!

UPDATE: have now corrected code as suggested below to:

dataset <- as.data.table(US_COVID19_study)

dataset[,ca_timechcare_categorical:= cut(survey_design_childcare,
                                                  breaks = c(36,72,108,Inf),
                                                  labels= c("Very_Low", "Low", "High", "Very_High"))]

dataset[,table(ca_timechcare_categorical)]

but now i get this error:

Error in `:=`(ca_timechcare_categorical, cut(survey_design_childcare,  : 
  Check that is.data.table(DT) == TRUE. Otherwise, := and `:=`(...) are defined for use in j, once only and in particular ways. See help(":=").

any ideas?? thanks again!


Solution

  • I assume you are using data.table and hence the vestigal operand := Two things: you are missing a comma in the brackets and its breaks not break

    library(data.table)
    irisdt <- as.data.table(iris)
    
    irisdt[,new := cut(Sepal.Width,
                       breaks=c(0,36,72,108,Inf),
                       include.lowest=TRUE,
                       labels=c("Very_Low", "Low", "High", "Very_High"))]