【问题标题】:Counting how many values are identical in two columns in R计算R中两列中有多少值相同
【发布时间】:2019-09-25 17:27:34
【问题描述】:

我有一个 df 和两个 DateTime 列:

entrance_date <- as.POSIXct(c("2014-03-12 08:44:18 UTC", "2015-09-16 02:56:00 UTC", "2015-10-24 08:09:11 UTC", "2016-12-11 17:17:00 UTC", "2017-08-06 18:26:00 UTC", "2018-01-29 00:00:00 UTC"))
item_date <- as.POSIXct(c("2014-04-17 08:40:10 UTC", "2015-09-16 02:56:00 UTC", "2015-11-12 13:15:00 UTC", "2016-12-16 17:10:09 UTC", "2017-08-10 04:11:00 UTC", "2018-01-29 00:00:00 UTC"))

df <- data.frame(entrance_date, item_date)
df
entrance_date           item_date
1 2014-03-12 08:44:18 2014-04-17 08:40:10
2 2015-09-16 02:56:00 2015-09-16 02:56:00
3 2015-10-24 08:09:11 2015-11-12 13:15:00
4 2016-12-11 17:17:00 2016-12-16 17:10:09
5 2017-08-06 18:26:00 2017-08-10 04:11:00
6 2018-01-29 00:00:00 2018-01-29 00:00:00

我可以通过识别它们的位置或通过它们的逻辑值来获得哪个rows 具有相同的DateTime 值:

> which(df$entrance_date == df$item_date)
[1] 2 6

> df$entrance_date == df$item_date
[1] FALSE  TRUE FALSE FALSE FALSE  TRUE

但是,我想count rows 在两个 columns 中具有相同值的数量。在这种情况下,计数应返回值 2。

非常感谢。

【问题讨论】:

    标签: r date datetime count


    【解决方案1】:

    我们可以使用sum 来包装逻辑向量,它会计算 TRUE 的数量,因为它被强制为二进制 1/0

    sum(df$entrance_date == df$item_date)
    #[1] 2
    

    如果我们使用which,则使用length进行包装

    length(which(df$entrance_date == df$item_date))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-22
      • 2018-12-24
      相关资源
      最近更新 更多