您可以使用data.table包輕鬆完成此操作。
library(data.table)
setDT(df)[, .SD[-1], by = ID]
# ID DATE N Price
# 1: 1 2013-03-18 1 9.99
# 2: 1 2013-04-13 2 19.99
# 3: 2 2013-05-11 2 19.99
其中df
是您的原始數據。這將刪除每個組的第一行,按ID
分組。
另一個選項是dplyr包。
library(dplyr)
slice(group_by(df, ID), -1)
# ID DATE N Price
# (int) (fctr) (int) (dbl)
# 1 1 2013-03-18 1 9.99
# 2 1 2013-04-13 2 19.99
# 3 2 2013-05-11 2 19.99
這些刪除所有組的第一行。如果組中只有一行,則不指定會發生什麼情況。如果您需要保留這些行,則需要對此進行說明。所以讓我們添加一行作爲一個組,並看看。
dff <- rbind(df, df[4, ])
dff[6, 1] <- 3
然後data.table代碼將是
setDT(dff)[, .SD[if(.N == 1L) 1 else -1], by = ID]
# ID DATE N Price
# 1: 1 2013-03-18 1 9.99
# 2: 1 2013-04-13 2 19.99
# 3: 2 2013-05-11 2 19.99
# 4: 3 2013-02-18 1 18.99
和dplyr代碼將是
slice(group_by(dff, ID), if(n() == 1L) 1 else -1)
# ID DATE N Price
# (dbl) (fctr) (int) (dbl)
# 1 1 2013-03-18 1 9.99
# 2 1 2013-04-13 2 19.99
# 3 2 2013-05-11 2 19.99
# 4 3 2013-02-18 1 18.99
用於這些情況。
數據:
df <- structure(list(ID = c(1L, 1L, 1L, 2L, 2L), DATE = structure(c(1L,
3L, 4L, 2L, 5L), .Label = c("2013-02-04", "2013-02-18", "2013-03-18",
"2013-04-13", "2013-05-11"), class = "factor"), N = c(3L, 1L,
2L, 1L, 2L), Price = c(29.99, 9.99, 19.99, 18.99, 19.99)), .Names = c("ID",
"DATE", "N", "Price"), class = "data.frame", row.names = c(NA,
-5L))
我喜歡它的簡單。我想出的最好的是'df [--match(unique(df $ ID),df $ ID)]],但這更好。 – thelatemail