简体   繁体   中英

Unable to convert type character to numeric in R

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 ie 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 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM