【问题标题】:Trouble in calculating minima by group in R在R中按组计算最小值的麻烦
【发布时间】:2018-05-29 11:16:13
【问题描述】:

使用here中的答案,我已经成功地按组计算了多次最小值和最大值。这次它不起作用,我不明白为什么。这是一个可重现的例子。

example <- structure(
  list(ID = 1:10, 
       date = 
         c("2005-05-09", "2006-09-18", "1996-06-14", "1997-01-06", 
           "1997-03-13", "1997-05-06", "1990-01-04", "1990-01-11", 
           "1989-12-28", "1989-12-28"), 
       name = c("a", "a", "a", "a", "a", "a", "b", "b", "b", "b")), 
  .Names = c("ID", "date", "name"), 
  class = c("data.table", "data.frame"), 
  row.names = c(NA, -10L))

example[example[, .I[which.min(date)], by=c("name")]$V1]

我期待的是这样的:

1996-06-14    a
1989-12-28    b

但是我得到一个空的数据表。为什么?

【问题讨论】:

  • example[, min(date), by=name]
  • 您的date 列是一个字符串。您需要先将其转换为 IDate 类,例如 example[, date := as.IDate(date)]

标签: r data.table grouping


【解决方案1】:

下面让:

library(data.table)
DT <- as.data.table(example)

1)如果您在代码中将date 替换为xtfrm(date),它将起作用。

DT[DT[, .I[which.min(xtfrm(date))], by=c("name")]$V1]

给予:

   ID       date name
1:  3 1996-06-14    a
2:  9 1989-12-28    b

2) 这为每个组只给出了一个最小值:

DT[, .SD[which.min(xtfrm(date))], by = name]

给予:

   name ID       date
1:    a  3 1996-06-14
2:    b  9 1989-12-28

3) 这给出了每个组的所有最小值:

DT[, .SD[date == min(date)], by = name]

给予:

   name ID       date
1:    a  3 1996-06-14
2:    b  9 1989-12-28
3:    b 10 1989-12-28

【讨论】:

  • 太棒了,谢谢! .SD 是什么意思?我以前从未见过。
  • 当使用 by= 时,它指的是当前行的子集,否则是所有行。
猜你喜欢
  • 1970-01-01
  • 2019-03-30
  • 2016-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
相关资源
最近更新 更多