【问题标题】:How to add a new column based on a few other variables如何根据其他一些变量添加新列
【发布时间】:2021-07-21 13:46:53
【问题描述】:

我是 R 新手,在使用现有变量的条件创建新变量时遇到问题。我有一个包含几列的数据集:名称、月份、性别二进制和价格。我想创建一个新变量 Price2,它将:

  1. 如果[月份为 6-9(6-9 月),性别为 0],则收取 20 的价格]
  2. 如果[月份为 6-9(6-9 月)且性别为 1],则收取 30 的价格]
  3. 如果[月份为 1-5(1-5 月)或月份为 10-12(10-12 月),则将收取的价格设为 0

--

structure(list(Name = c("ADI", "SLI", "SKL", "SNK", "SIIEL", "DJD"), Mon = c(1, 2, 3, 4, 5, 6), Gender = c(1, NA, NA, NA, 1, NA), Price = c(23, 34, 32, 64, 23, 34)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"))

【问题讨论】:

  • 请提供您的数据集示例,或提供以下dput(head(mydf)) 的输出,其中mydf 是您的数据框的名称。
  • 结构(列表(名称 = c(“ADI”、“SLI”、“SKL”、“SNK”、“SIIEL”、“DJD”),Mon = c(1, 2, 3 , 4, 5, 6), 性别 = c(1, NA, NA, NA, 1, NA), 价格 = c(23, 34, 32, 64, 23, 34)), row.names = c(NA , -6L), class= c("tbl_df", "tbl", "data.frame"))
  • 数据集有48个条目

标签: r if-statement case-when


【解决方案1】:

使用dplyr 包中的case_when()

mydf$newprice <- dplyr::case_when(
  mydf$Mon >= 6 & mydf$Mon <= 9 & mydf$Gender == 0 ~ 20,
  mydf$Mon >= 6 & mydf$Mon <= 9 & mydf$Gender == 1 ~ 30,
  mydf$Mon < 6 | mydf$Mon > 9 ~ 0)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2022-12-17
    • 2015-10-01
    相关资源
    最近更新 更多