gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 11:03:42 24 4
gpt4 key购买 nike

我有这样的数据,其中一些“名称”出现了三遍以上:

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)

最佳答案

首先,两个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]

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

关于r - 基于每组行数的子集数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20204257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com