Search code examples
rdatasetmultiple-columns

Is there a function in R to convert the units of multiple columns with a built in dataset


New to R programming and trying to get familiar with the various functions using the built in datasets.

Using the 'women' dataset, I want to change the units of measure to the metric system. The first column from in to cm and the second from lbs to kg.

I believe I can change the units using these commands, but am having difficulty applying it to the columns of the 'women' dataset. Or are there better commands to convert units in a dataset?

Thanks!

w<-as_tibble(women)

in2cm <- function(length) {
cm <- length/2.54
return(cm)
}
lbs2kg <- function(mass) {
kg <- mass*0.45
return(kg)
}

Solution

  • Using your current functions the simplest way you can reassign the columns is like this:

    w$height = in2cm(w$height)
    w$weight = lbs2kg(w$weight)
    

    Also your in2cm() is a slightly off. You should multiply instead of divide - I'm sure it was just a minor typo!

    in2cm <- function(length) {
      cm <- length*2.54
      return(cm)
    }