sherek_66
sherek_66

Reputation: 531

How to convert different units to one?

I have a dataframe with two columns: one is the amount of money the other one is unite : per day, per week, per month and per year how I can make all of them per day?

Data:

   PAYPR         UNIT
    40       (4) Per month
    100      (5) Per semester
    50       (6) Per year
    5        (1) Per day

I know if it was just 2 units: "(4) Per month", "(1) Per day" I could do this :

  with(df, ifelse(UNIT != '(4) Per month', PAYPR * 30, PAYPR))

output:

   PAYPR         UNIT               uniqe
    40       (4) Per month          40*30
    100      (5) Per semester       100*90
    50       (6) Per year           50*360
    5        (1) Per day            5*1

Upvotes: 0

Views: 545

Answers (2)

Cettt
Cettt

Reputation: 11981

you can use case_when from the dplyr package:

library(dplyr)
df %>%
  mutate(unique = PAYPR * case_when(UNIT == "(4) Per month" ~ 30, 
                                    UNIT == "(5) Per semester" ~ 90,
                                    UNIT == "(6) Per year" ~ 360,
                                    UNIT == "(1) Per day" ~ 1))

Upvotes: 1

akrun
akrun

Reputation: 887158

It would be easier to create a key/val dataset and join. Note that this can be extended to any number of entries

library(fuzzyjoin)
library(dplyr)
df2 <- data.frame(key = c("month", "semester", "year", "day"),
      val = c(30, 90, 360, 1))
regex_left_join(df1, df2, by = "UNIT") %>% 
    mutate(uniqe = PAYPR *val) %>%
   select(PAYPR, UNIT = UNIT.x, uniqe)
#  PAYPR             UNIT uniqe
#1    40    (4) Per month  1200
#2   100 (5) Per semester  9000
#3    50     (6) Per year 18000
34     5      (1) Per day     5

data

df1 <- structure(list(PAYPR = c(40L, 100L, 50L, 5L), UNIT = c("(4) Per month", 
"(5) Per semester", "(6) Per year", "(1) Per day")), 
   class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 2

Related Questions