问题描述
我有这样的数据,其中一些名称出现超过3次:
I have data like this, where some "name" occur more than 3 times:
df <- data.frame(name = c("a", "a", "a", "b", "b", "c", "c", "c", "c"), x = 1:9)
我希望根据名称的每个级别中的行数(观察值)对数据进行子集变量。如果某个级别的名称发生超过说3次,我想删除属于该级别的所有行。
I wish to subset the data based on number of rows (observations) within each level of the "name" variable. If a certain level of "name" occurs more than say 3 times, I want to remove all rows belonging to that level.
我写了这段代码,但无法让它工作。
I wrote this code, but can't get it to work.
as.data.frame(table(unique(df)$name))
subset(df, name > 3)
提前感谢
推荐答案
以下是使用 base
R的前两种方法。一种依赖于表
,另一个在 ave
和长度
之间。最后一个 data.table
版本。
Here are first two ways using base
R. One relies on table
, and the other on ave
and length
. Finally a data.table
version.
tt <- table(df$name)
df2 <- subset(df, name %in% names(tt[tt < 3]))
# or
df2 <- df[df$name %in% names(tt[tt < 3]), ]
如果你想一步步走一步:
If you want to walk it through step by step:
# 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。 ave
和长度
根据@flodel的建议:
2. ave
and length
As suggested by @flodel:
df[ave(df$x, df$name, FUN = length) < 3, ]
3。 data.table ::。N
3. data.table::.N
library(data.table)
setDT(df)[, if (.N < 3) .SD, by = name]
另见相关问答< a href =http://stackoverflow.com/questions/7450600/count-number-of-observations-rows-per -group-and-add-result-to-data-frame>计算每组观察值/行数,并将结果添加到数据帧。
这篇关于基于每组的行数子集数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!