I have a column in a R dataframe that holds a product weight i.e. 20 kg but it has mixed measuring systems i.e. 1 lbs & 2 kg etc. I want to separate the value from the measurement and put them in separate columns then convert them in a new column to a standard weight. Any thoughts on how I might achieve that? Thanks in advance.
-
2Please add clear sample data, and then also show us the output you want. – Tim Biegeleisen Jun 17 '21 at 07:02
-
1It is helpful to provide a sample of your data in order to provide a [good reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You can provide a sample by using `dput(head(df))`. – AndrewGB Jun 17 '21 at 07:08
-
Thanks and apologies - I am still finding my way around here. I did manage in the end to do it using separate(MyData, bag_weight, into = c("Value", "Metric") and that worked for me. Thanks for the tip on dput though - very handy! – MorneLippiatt Jun 17 '21 at 16:29
2 Answers
Assume you have the column given as
x <- c("20 kg","50 lbs","1.5 kg","0.02 lbs")
and you know that there is always a space between the number and the measurement. Then you can split this up at the space-character, e.g. via
splitted <- strsplit(x," ")
This results in a list of vectors of length two, where the first is the number and the second is the measurement. Now grab the numbers and convert them via
numbers <- as.numeric(sapply(splitted,"[[",1))
and grab the units via
units <- sapply(splitted,"[[",2)
Now you can put everything together in a `data.frame.
Note: When using as.numeric
, the decimal point has to be a dot. If you have commas instead, you need to replace them by a dot, for example via gsub(",","\\.",...)
.

- 1,760
- 1
- 3
- 12
-
Thanks for the help - my data was already in a dataframe so I ended using separate(MyData, bag_weight, into = c("Value", "Metric") – MorneLippiatt Jun 17 '21 at 16:13
separate(DataFrame, VariableName, into = c("Value", "Metric"), sep = " ")
My case was simple enough that I could get away with just one space separator but I learned you can also use a regular expression here for more complex separator considerations.

- 3
- 3