【问题标题】:How to create a new column where it takes value of another column when another column's condition is satisfied当满足另一列的条件时,如何创建一个新列,该列取另一列的值
【发布时间】:2018-07-27 06:17:35
【问题描述】:

所以我有一个数据集,其中有帐号、报告日期和默认标志。 我想创建一个新列,如果默认标志==1,则新列应选择该日期,否则为 0。

Reporting date Default Flag Account Number
31-05-2006          1
30-06-2006          0
31-07-2006          0
31-08-2006          1
30-09-2006          0
31-10-2006          0
30-11-2006          1
31-12-2006          0
31-01-2007          0 

所以每个帐号都有多个条目,我想要一个新列,每当默认标志命中 ==1 时提取日期。

提前致谢! :)

【问题讨论】:

  • ifelse(df$default_flag, df$Reporting_Date, 0) ?

标签: r extract data-analysis data-manipulation


【解决方案1】:

另一种方法是将所有值设置为 0,然后更改满意的值:

df[3] <- c(0,nrow(df))
D[D[,2]==1,3]=D[D[,2]==1,1]

【讨论】:

    【解决方案2】:

    我们可以在这里使用ifelse

    df$new_date <- ifelse(df$`Default Flag` == 1, df$`Reporting date`, 0)
    

    顺便说一句,我不知道您的列名中是否真的有空格,但如果有,那么您需要在反引号中转义整个名称。这可能会导致代码难看,所以可能会坚持使用没有空格的单一名称。

    【讨论】:

      猜你喜欢
      • 2021-08-25
      • 2017-10-14
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-17
      • 2018-09-13
      相关资源
      最近更新 更多