【问题标题】:Subsetting a data.frame based on a condition in R [duplicate]根据R中的条件对data.frame进行子集[重复]
【发布时间】:2016-07-28 00:58:41
【问题描述】:

我想根据 r 中的条件对data.frame 进行子集化。我有以下data.frame

df

id     |    message      |     cluster
-------+-----------------+----------------
1      | Test A          | 1
2      | Test B          | 1
3      | Test C          | 3
4      | Test D          | 1
5      | Test E          | 2 
6      | Test F          | 2
7      | Test G          | 3
8      | Test H          | 3
9      | Test I          | 1 
10     | Test K          | 2
11     | Test L          | 4
12     | Test M          | 4

我想构造一个新的data.frame,它有 4 行(不同簇的数量)。我选择第一个message 作为集群的代表。所以我想得到以下data.frame

df2

id     |    message      |     cluster
-------+-----------------+----------------
1      | Test A          | 1
3      | Test C          | 3
5      | Test E          | 2 
11     | Test L          | 4

【问题讨论】:

  • df2 <- do.call(rbind, by(df, df$cluster, function(x) head(x, 1)))
  • 请以可重复的格式提供您的示例数据,例如dput
  • df2 <- df[!duplicated(df$cluster), ] 都可以。

标签: r dataframe


【解决方案1】:

作为一种替代方法,dplyr 包非常适合这类事情。

text <- "id     |    message      |     cluster
1      | Test A          | 1
2      | Test B          | 1
3      | Test C          | 3
4      | Test D          | 1
5      | Test E          | 2
6      | Test F          | 2
7      | Test G          | 3
8      | Test H          | 3
9      | Test I          | 1
10     | Test K          | 2
11     | Test L          | 4
12     | Test M          | 4"

library(readr)
df <- read_delim(text, delim = "|", trim_ws=TRUE) 

library(dplyr)
df2 <-
    df %>% 
    group_by(cluster) %>%
    summarize(message=first(message))

结果如下:

> df2
# A tibble: 4 x 2
  cluster message
    <int>   <chr>
1       1  Test A
2       2  Test E
3       3  Test C
4       4  Test L

arrange 数据可能很有用,以便“第一”是可预测的。)

【讨论】:

    【解决方案2】:

    获取要收集的行的索引:

    indices <- !duplicated(df$cluster)
    

    使用它来子集数据框:

    df2 <- df[indices, ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-25
      • 2016-02-12
      • 2020-09-09
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多