I have a column month which was import as a char type within a data.table, for instant "January" "March" etc. In this column also contain some missing data NA.
I am using the below code to convert it to integer month:
dt <- dt[!is.na(month), month := match(month, month.abb)]
I got warning in console:
Warning message:
In `[.data.table`dt, !is.na(month), `:=`(month, :
Coerced integer RHS to character to match the type of the target column (column 9 named 'month'). If the target column's type character is correct, it's best for efficiency to avoid the coercion and create the RHS as type character. To achieve that consider R's type postfix: typeof(0L) vs typeof(0), and typeof(NA) vs typeof(NA_integer_) vs typeof(NA_real_). You can wrap the RHS with as.character() to avoid this warning, but that will still perform the coercion. If the target column's type is not correct, it's best to revisit where the DT was created and fix the column type there; e.g., by using colClasses= in fread(). Otherwise, you can change the column type now by plonking a new column (of the desired type) over the top of it; e.g. DT[, `month`:=as.integer(`month`)]. If the RHS of := has nrow(DT) elements then the assignment is called a column plonk and is the way to change a column's type. Column types can be observed with sapply(DT,typeof).
Also, the value of month column became NA . Any idea? thank you very much.
table look like
month |year |
September| 1987 |
March | 1999 |
Expect change to :
month |year |
9 | 1987 |
3 | 1999 |
Final change and work:
dt[!is.na(month), month := match(month, month.name)]