How to convert a column in a data frame to numeric

So I’m working in this table:

Raumeinheit Langzeitarbeitslose
Hamburg 33,23
Berlin 44,56

I’m trying to calculate the mean of Langzeitarbeitslose but I can’t because


comes out as false because the column Langzeitarbeitslose is defined as character.

I think this might be because here in Germany we use "," to show decimals and not "."

I already tried

as.numeric(gsub(",", ".", West_data$Langzeitarbeitslose))

that gave me a working table in the console preview but when I looked at the table with


It still showed the Decimals of Langzeitarbeitslose seperated with ‘,’ and


came back as false.

>Solution :

I guess you need to assign the result of as.numeric(gsub(",", ".", West_data$Langzeitarbeitslose)) to the column West_data$Langzeitarbeitslose

West_data$Langzeitarbeitslose <- as.numeric(gsub(",", ".", West_data$Langzeitarbeitslose))

The result of print(West_data) will be:

  Raumeinheit Langzeitarbeitslose
1     Hamburg               33.23
2      Berlin               44.56

The cast of datatype can be checked here:

> str(West_data)
'data.frame':   2 obs. of  2 variables:
 $ Raumeinheit        : chr  "Hamburg" "Berlin"
 $ Langzeitarbeitslose: num  33.2 44.6

Leave a Reply