你如何根据 R 中的条件分离小标题?

how do you separate a tibble based on a condition in R?

说,我有以下问题;

df <- tibble(name = c("CTX_M", "CblA_1", "OXA_1", "ampC"),
             rpkm = c(350, 4, 0, 0))

我想将 tibble 拆分为一个 rpkm = 0 和另一个 rpkm > 0。

我尝试创建一个函数来 select rpkm = 0 的行,如下所示

zero <- function(data){
  input = data
  if(input[, 2] == 0){
    n = input
    print(n)
  }
}

但是当我尝试 运行 时出现以下错误

Zero <- zero(df)

Warning message:
In if (input[, 2] == 0) { :
  the condition has length > 1 and only the first element will be used

由于我对 R 不太熟悉,所以我不确定出了什么问题,或者如何解决这个问题?

或者,您可以使用一个名为 'dplyr' 的便捷包,它是 tidyverse 包系列的一部分。他们有很多处理数据的方便函数。

#library of interest
library(dplyr)

##Your data
df <- tibble(name = c("CTX_M", "CblA_1", "OXA_1", "ampC"),
             rpkm = c(350, 4, 0, 0))

##Using the filter function to get all = 0
df_filt1 <- df %>% 
  filter(rpkm == 0)

##see what the filtering looks like
df_filt1

# A tibble: 2 x 2
  name   rpkm
  <chr> <dbl>
1 OXA_1     0
2 ampC      0

##Using the filter function to get all > 0
df_filt2 <- df %>% 
  filter(rpkm > 0)

##see what the filtering looks like
df_filt2

# A tibble: 2 x 2
  name    rpkm
  <chr>  <dbl>
1 CTX_M    350
2 CblA_1     4