Search code examples
rregexstringunits-of-measurementpad

How to insert "1 " in the start for a column in R?


I have a column in my data (master_data) called unit.

master_data$unit <- c("Tonnes","1000 Tonnes","Numbers","1000 Numbers")

I want to transform this column such that I get this

master_data$unit <- c("1 Tonnes","1000 Tonnes","1 Numbers", "1000 Numbers")

I want to do this so that I can split the unit it into two columns, 1/1000s and Tonnes/Numbers

I tried to find the length of the unit and then use paste command, but it doesn't work

master_data$unit_len <- sapply(strsplit(master_data$unit, " "), length)


if (master_data$unit_len == 1) {
  paste("1 ", master_data$unit, sep="")
}

However, this doesn't work.


Solution

  • Check if unit begins with a number. If not, paste 1 at the beginning

    unit <- c("Tonnes","1000 Tonnes","Numbers","1000 Numbers")
    ifelse(grepl("^\\d", unit), unit, paste("1", unit))
    #[1] "1 Tonnes"     "1000 Tonnes"  "1 Numbers"    "1000 Numbers"