基于每组行数的子集数据帧

时间:2013-11-25 21:59:58

标签: r dataframe subset r-faq

我有这样的数据,其中一些“名称”出现超过3次:

df <- data.frame(name = c("a", "a", "a", "b", "b", "c", "c", "c", "c"), x = 1:9)

  name x
1    a 1
2    a 2
3    a 3
4    b 4
5    b 5
6    c 6
7    c 7
8    c 8
9    c 9

我希望根据name变量的每个级别中的行数(观察值)对数据进行子集化(过滤)。如果某个级别的name发生超过3次,我想删除属于该级别的所有行。因此,在此示例中,我们会将观察结果放在name == c,因为该组中有> 3行:

  name x
1    a 1
2    a 2
3    a 3
4    b 4
5    b 5

我写了这段代码,但无法让它工作。

as.data.frame(table(unique(df)$name))
subset(df, name > 3)

4 个答案:

答案 0 :(得分:39)

首先,两个base替代方案。一个依赖table,另一个依赖avelength。然后,两个data.table方式。


1。 table

tt <- table(df$name)

df2 <- subset(df, name %in% names(tt[tt < 3]))
# or
df2 <- df[df$name %in% names(tt[tt < 3]), ]

如果你想逐步完成它:

# count each 'name', assign result to an object 'tt'
tt <- table(df$name)

# which 'name' in 'tt' occur more than three times?
# Result is a logical vector that can be used to subset the table 'tt'
tt < 3

# from the table, select 'name' that occur < 3 times
tt[tt < 3]

# ...their names
names(tt[tt < 3])

# rows of 'name' in the data frame that matches "the < 3 names"
# the result is a logical vector that can be used to subset the data frame 'df'
df$name %in% names(tt[tt < 3])

# subset data frame by a logical vector
# 'TRUE' rows are kept, 'FALSE' rows are removed.
# assign the result to a data frame with a new name
df2 <- subset(df, name %in% names(tt[tt < 3]))
# or
df2 <- df[df$name %in% names(tt[tt < 3]), ]

2。 avelength

正如@flodel所建议的那样:

df[ave(df$x, df$name, FUN = length) < 3, ]

3。 data.table.N.SD

library(data.table)
setDT(df)[, if (.N < 3) .SD, by = name]

4。 data.table.N.I

setDT(df)
df[df[, .I[.N < 3], name]$V1] 

另请参阅相关的问答Count number of observations/rows per group and add result to data frame

答案 1 :(得分:24)

使用dplyr包:

df %>%
  group_by(name) %>%
  filter(n() < 4)

# A tibble: 5 x 2
# Groups:   name [2]
  name      x
  <fct> <int>
1 a         1
2 a         2
3 a         3
4 b         4
5 b         5

n()返回当前组中的观察数,因此我们可以group_by命名,然后只保留属于该组中行数的组的一部分的行比4。

答案 2 :(得分:1)

使用dpylr包的另一种方法是使用count函数,然后对原始数据帧进行半连接:

library(dplyr)

df %>% 
  count(name) %>%
  filter(n <= 3) %>%
  semi_join(df, ., by = "name")

答案 3 :(得分:0)

软件包“ inops”具有一些有用的中缀运算符。对于这种特殊情况,操作员%in#%可以根据元素出现的次数选择元素。

library(inops)

df[df$name %in#% 1:3,]

哪个返回:

  name x
1    a 1
2    a 2
3    a 3
4    b 4
5    b 5

这里df$name %in#% 1:3仅对出现1、2或3次的元素返回TRUE。相反,如果我们想选择出现4次的元素,我们将这样做:

df[df$name %in#% 4,]

具有以下结果:

  name x
6    c 6
7    c 7
8    c 8
9    c 9
相关问题