如何将不同单位转换为一个?

时间:2019-07-05 13:57:11

标签: r dataframe

我有一个包含两列的数据框:一是金额,另一列是单位:每天,每周,每月和每年如何才能每天将它们全部制成?

数据:

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

我知道是否只有2个单位:“每月(4)”,“每天(1)”我可以这样做:

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

输出:

   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

2 个答案:

答案 0 :(得分:2)

创建键/值数据集并进行连接会更容易。请注意,这可以扩展到任意数量的条目

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

数据

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))

答案 1 :(得分:1)

您可以使用dplyr软件包中的case_when

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))