【问题标题】:How to create a new column based on the NAs and ZEROs of multiple other columns in R?如何根据 R 中多个其他列的 NA 和 ZERO 创建新列?
【发布时间】:2020-10-23 09:20:49
【问题描述】:

我有一个数据集,可以跟踪数百万家公司多年来的收入。数据看起来像下面的简化版本:

dat <-   data.frame(Company = c("a","b","c","d","e","f"), rev_2001 = c(NA, 20, 10, NA, NA, 10), 
     rev_2002 = c(10, 50, 20, 30, NA, 0), rev_2003 = c(20, NA, 0, NA, NA, 30), rev_2004 = c(NA, 60, 0, 50, NA, 50), rev_2005 = c(NA, 30, NA, 0, NA, 60))

我想创建一个变量(一个我们可以标记为“closure.year”的新列)来记录公司去年的收入不是 0 或 NA。我正在为两件事苦苦挣扎:

  1. 我想忽略零和 NA,但我不想将 NA 转换为零,也不想反过来;
  2. 如您所见,数据有一些零和 NA,不仅在观察到的最后几年,而且在一些中间年份。如果公司在 0 或 NA 一年后有收入,则该年不会被视为关闭年。此外,如果公司没有停止接收收入,则变量 closure.year 将为 NA。

总之,我希望得到如下所示的最终数据:

非常感谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    你可以试试下面的代码

    z <- do.call(cbind,Reduce(`|`,rev(replace(dat,is.na(dat),0)[-1]),accumulate = TRUE))
    x <- max.col(z>0,"first")
    dat$closure.year <- as.numeric(gsub(".*_","",names(dat[-1])[ncol(dat)-replace(x,x == 1,NA)]))
    

    给了

    > dat
      Company rev_2001 rev_2002 rev_2003 rev_2004 rev_2005 closure.year
    1       a       NA       10       20       NA       NA         2003
    2       b       20       50       NA       60       30           NA
    3       c       10       20        0        0       NA         2002
    4       d       NA       30       NA       50        0         2004
    5       e       NA       NA       NA       NA       NA           NA
    6       f       10        0       30       50       60           NA
    

    【讨论】:

      【解决方案2】:

      如何从宽格式转换为长格式?

      df_long <- gather(df,year,value,rev_2001:rev_2005,factor_key=TRUE)
      df_long %>% group_by(Company) %>% top_n(1, value)
      

      您需要添加更多逻辑来处理您的 0 和 NA 条件,但这种方法可能会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-05
        • 1970-01-01
        • 2019-06-13
        • 2023-01-24
        • 2022-09-23
        • 1970-01-01
        相关资源
        最近更新 更多