【问题标题】:r- sum unique values in aggregate function and use NA as 0r-汇总函数中的唯一值并将NA用作0
【发布时间】:2014-12-20 10:41:36
【问题描述】:

我有一张这样的桌子:

ppp<-data.frame(client=c(1,1,1,3,3,4), 
                calldate=c('2014-08-07', NA,'2014-08-06',NA, '2014-08-08',NA),
                paydate=c('2014-08-07', '2014-08-09', NA, '2014-08-06',NA,'2014-08-06' ))

我需要获取每个客户的通话日期计数。我试过了:

my.fun<-function (x) {sum(!is.na(unique(x)))}
ppp2<-aggregate(calldate~(client+calldate) , ppp, my.fun)

我明白了:

> ppp2
  client calldate
      1        2
      3        1

如您所见,我失去了 3 号客户,我必须拥有所有客户,如果他们没有接到电话,则归零。

  client calldate
      1        2
      3        1
      3        0

如何计算日期,如果没有日期,则输入 0? 我也试过:

my.fun<-function (x) {length(unique(x))}

得到了同样的结果

我也尝试了以下方法:

my.fun<-function (x) {if (is.na(x)) {0} else {length(unique(x))}}

我得到一个错误:

警告信息:在 if (is.na(x)) { : 条件长度 > 1 并且只使用第一个元素

【问题讨论】:

    标签: r function conditional-statements aggregate


    【解决方案1】:

    如果您使用参数na.action = na.pass,它会起作用。否则,aggregate 将忽略 NA 值。

    aggregate(calldate ~ client, ppp, my.fun, na.action = na.pass)
    #   client calldate
    # 1      1        2
    # 2      3        1
    # 3      4        0
    

    【讨论】:

      猜你喜欢
      • 2022-07-24
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 2018-04-23
      • 1970-01-01
      • 2018-06-09
      • 1970-01-01
      相关资源
      最近更新 更多