-1

The columns in my data frame are stored as characters. I get an error when i use the aggregate function because of using the operation on characters. I could find a similar question but the solution provided i.e as.numeric(as.character(dataframe)) does not work for me. How do I change the type of my column and also retain the column's value?

> str(df$Order_Quantity)
  chr [1:92] "1,909.60" "2,019.20" "4,119.60" "-" "11,000.00" "1110.00"  "80.5" ...
> df$Order_Quantity<- as.numeric(as.character(df$Order_Quantity))
 Warning message:
 NAs introduced by coercion 
> str(df$Order_Quantity)
 num [1:92] NA NA NA NA NA NA 10.5 NA NA 26 ...
#I am losing my data 

1 Answer 1

1

Remove the commas using gsub():

df$Order_Quantity<- as.numeric(gsub(",", "", as.character(df$Order_Quantity)))

I also noticed that your source data appears to have a dash (-) as well. You can ignore this and it will simply be replaced with NA, or you can handle it as you see fit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.