【问题标题】:Filter rows by group level in R在 R 中按组级别过滤行
【发布时间】:2021-12-21 14:20:51
【问题描述】:

如何选择与 2006 年、2019 年和 2020 年相关联的所有行(也保留带有 NA 的行)?

> head(all_data)
      year     Tt
      <fct> <dbl>
    1 2006   NA  
    2 2020    5  
    3 2008   18  
    4 2018   41  
    5 2020   33.5
    6 2019    0.7

我试过这个方法,但我得到一个错误:

mini_data <- all_data[(all_data$year==c('2020','2019','2006')),]

Warning messages:
1: In `==.default`(rand$year, c("2020", "2019", "2006")) :
  longer object length is not a multiple of shorter object length
2: In is.na(e1) | is.na(e2) :
  longer object length is not a multiple of shorter object length

【问题讨论】:

  • %in%替换==
  • 你太棒了,谢谢!

标签: r subset


【解决方案1】:

结合“哪个”与“|”操作员为我解决了这个问题。

mini_data <- data[which(data$year== 2020 | data$year == 2019 | data$year == 2006),]

可以在此处找到有关此主题的优秀帖子:How to combine multiple conditions to subset a data-frame using "OR"?

【讨论】:

    猜你喜欢
    • 2021-12-13
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多