0

I'm trying to convert character values (including those with decimal values) to numeric but it loses the decimal 0 and just converts it to integer:

results <- c("600.0","600","50","50.0","unknown","300xx300")
df <- data.frame(MIX = results, NUM_ONLY = as.numeric(results))

How can I change it so that it looks like this:

df2<- data.frame(MIX = results ,NUM_ONLY = c("600.0","600","50","50.0",NA,NA))
karuno
  • 391
  • 4
  • 12
  • Does this answer your question? [How to convert a factor to integer\numeric without loss of information?](https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-integer-numeric-without-loss-of-information) – NelsonGon Mar 08 '20 at 06:12
  • you cannot have values of mixed datatypes in one-column. You can do some string manipulation to achieve the desired output as shown but I don't think that would be helpful if you want to use those numbers ahead. – Ronak Shah Mar 08 '20 at 06:13
  • I think the default in future R will be `stringsAsFactors`=FALSE. That is the main issue here I think. Like so: `df <- data.frame(MIX = results,stringsAsFactors = F) as.numeric(as.character(df$MIX))` – NelsonGon Mar 08 '20 at 06:13

1 Answers1

0

Using ifelse make those NA that yield NA when coercing to numeric. The result is class "character" though, since decimal zeros are not possible as "numeric". I would stick to your own solution, which by the way is not "integer" but "numeric", try e.g. with c("600.1","600","50","50.0","unknown","300xx300").

data.frame(results,
           NUM_ONLY=suppressWarnings(ifelse(is.na(as.numeric(results)), NA, results)))
#    results NUM_ONLY
# 1    600.0    600.0
# 2      600      600
# 3       50       50
# 4     50.0     50.0
# 5  unknown     <NA>
# 6 300xx300     <NA>
jay.sf
  • 60,139
  • 8
  • 53
  • 110