【问题标题】:how do you separate a tibble based on a condition in R?你如何根据 R 中的条件分离小标题?
【发布时间】:2020-04-27 11:32:18
【问题描述】:

说,我有以下小标题;

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

我想将 tibble 分成一个 rpkm = 0 和一个 rpkm > 0 的第二个。

我尝试创建一个函数来选择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,我不确定出了什么问题,或者如何解决这个问题?

【问题讨论】:

  • split(df, df$rpkm &gt; 0)

标签: r tibble


【解决方案1】:

或者,您可以使用一个名为“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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    相关资源
    最近更新 更多