I have a dataframe where one character-variable looks like the following:
Var1
10 km
100 m
2.7 km
3 km
500 m
What would be the best approach to transform this variable into a numeric one but also convert all values that are kilometers into meters?
Var1 <- c("10 km", "100 m", "2.7 km", "3 km", "500 m")
strsplit(Var1, " ")
sapply(strsplit(Var1, " "), function(x) ifelse(x[2] == "km", as.numeric(x[[1]])*1000, as.numeric(x[[1]])))
[1] 10000 100 2700 3000 500
This solution only accepts "m" and "km" as unit. If you need further units, you can just define your own function to do the mapping.