如何在 R 中的频率表后删除数据框中的行

5

我有三个数据框,需要找出拥有小于2个国家的大陆并删除这些国家(行)。这些数据框的结构类似于下面的一个名为x的数据框:

    row        Country   Continent   Ranking
    1        Kenya       Africa      17
    2        Gabon       Africa      23
    3        Spain       Europe      04
    4        Belgium     Europe      03
    5        China       Asia        10
    6        Nigeria     Africa      14
    7        Holland     Europe      01
    8        Italy       Europe      05
    9        Japan       Asia        06

首先,我想知道每个大洲的每个国家的频率,所以我进行了以下操作:

    x2<-table(x$Continent)
    x2
    Africa Europe Asia
    3        4      2

然后我想识别拥有少于2个国家的大陆。

    x3 <- x2[x2 < 10]
    x3
    Asia
    2  

我的问题现在是如何删除这些国家。对于上面的例子,将是亚洲的两个国家,我希望我的最终数据集看起来像下面呈现的:

    row       Country   Continent   Ranking
    1        Kenya       Africa      17
    2        Gabon       Africa      23
    3        Spain       Europe      04
    4        Belgium     Europe      03
    5        Nigeria     Africa      14
    6        Holland     Europe      01
    7        Italy       Europe      05

拥有少于2个国家的大陆数量在不同数据框中会有所变化,因此我需要一种通用方法来适用于所有数据。


我认为你的代码是 x2[x2<=2] - akrun
2个回答

5

尝试

 library(dplyr)
 x %>%
    group_by(Continent) %>% 
    filter(n()>2)
 #   row Country Continent Ranking
 #1   1   Kenya    Africa      17
 #2   2   Gabon    Africa      23
 #3   3   Spain    Europe      04
 #4   4 Belgium    Europe      03
 #5   6 Nigeria    Africa      14
 #6   7 Holland    Europe      01
 #7   8   Italy    Europe      05

或者使用 x2

 subset(x, Continent %in% names(x2)[x2>2])
 #    row Country Continent Ranking
 #1   1   Kenya    Africa      17
 #2   2   Gabon    Africa      23
 #3   3   Spain    Europe      04
 #4   4 Belgium    Europe      03
 #6   6 Nigeria    Africa      14
 #7   7 Holland    Europe      01
 #8   8   Italy    Europe      05

3
用"data.table"实现非常简单,代码如下:
library(data.table)
as.data.table(x)[, N := .N, by = Continent][N > 2]
#    row Country Continent Ranking N
# 1:   1   Kenya    Africa      17 3
# 2:   2   Gabon    Africa      23 3
# 3:   3   Spain    Europe       4 4
# 4:   4 Belgium    Europe       3 4
# 5:   6 Nigeria    Africa      14 3
# 6:   7 Holland    Europe       1 4
# 7:   8   Italy    Europe       5 4

在基础 R 中,你可以尝试:
x[with(x, ave(rep(TRUE, nrow(x)), Continent, FUN = function(y) length(y) > 2)), ]
#   row Country Continent Ranking
# 1   1   Kenya    Africa      17
# 2   2   Gabon    Africa      23
# 3   3   Spain    Europe       4
# 4   4 Belgium    Europe       3
# 6   6 Nigeria    Africa      14
# 7   7 Holland    Europe       1
# 8   8   Italy    Europe       5

1
setDT(x)[, .SD[.N>2] , Continent] 可能更短但也更慢。 - akrun
谢谢,但我还有一个问题。如果大陆包含一些NA值,您如何删除缺少大陆值的国家?@akrun - user4888445
@patience,你的意思是“删除那些在'Continents'列中少于两个或带有NA值的行”吗? - A5C1D2H2I1M1N2O1R2T1
@patience 不清楚你想要什么。如果你需要删除大陆中的NA行。x$Continent[3] <- NA; subset(x, !is.na(Continent)) - akrun

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接