How to coerce column to be numeric with merged values

Viewed 26

I have a large data set in which one of the columns is monetary, however the values in that column have different patterns, so that when I try to apply as.numeric some values become missings.

Specifically, I have:

structure(list(test = c("200.09", "409.12", "00456,12", "00456,15"
)), class = "data.frame", row.names = c(NA, -4L))

when I apply as.numeric, I get a new column like:

structure(list(test = c("200.09", "409.12", "00456,12", "00456,15"
), test_numeric = c(200.09, 409.12, NA, NA)), row.names = c(NA, 
-4L), class = "data.frame")

However, I would like to obtain:

structure(list(test = c("200.09", "409.12", "00456,12", "00456,15"
), test_numeric = c(200.09, 409.12, 456.12, 456.15)), row.names = c(NA, 
-4L), class = "data.frame")

I appreciate any help.

1 Answers

The , is considered to be character and changes the whole column to type character. We can replace with . and convert.

df1$test_numeric <- as.numeric(sub(",", ".", df1$test))

Other option is while reading the data, specify the dec = ','. With read.table/read.csv the default option is dec = '.', whereas in read.delim2/read.csv2, it is dec =','

Related