【问题标题】:Removing columns from dataframe that have value greater than -1从数据框中删除值大于 -1 的列
【发布时间】:2021-08-31 12:45:15
【问题描述】:

我正在尝试删除所有存在的值都大于 -1 的列(例如:-0.45 或 0.45)。但是,如果至少有一行的值等于或小于 -1(例如:-1.14),我想保留这些列。

我尝试了以下方法,但在数据表中出现错误:

i evaluates to a logical vector length 17645 but there are 24 rows. Recycling of logical i is no longer allowed as it hides more bugs than is worth the rare convenience. Explicitly use rep(...,length=.N) if you really need to recycle. 

原始DF(示例)

Cell    Gene1    Gene2      Gene3     Gene4      Gene5
Cell1   0.02    -1.100.2    0.002   -1.772.1    -0.0884
Cell2   0.19    -1.098.0    0.068   -1.837.0    0.0685
Cell3   0.13    -1.328.7    -1.580  -1.687.6    0.2554
Cell4   -0.032  -1.245.3    0.004   -1.528.4    -0.2037

所需的 DF(示例)

Cell    Gene2       Gene3     Gene4   
Cell1   -1.100.2    0.002   -1.772.1    
Cell2   -1.098.0    0.068   -1.837.0    
Cell3   -1.328.7    -1.580  -1.687.6    
Cell4   -1.245.3    0.004   -1.528.4    

过滤值的命令

desired_df <- original_df[sapply(original_df, function(x) max(x) <= -1)]

【问题讨论】:

标签: r dplyr tidyverse


【解决方案1】:

您还可以使用purrr 中的keep()discard()(在tidyverse 中)。您可以将它们与any()all() 结合使用。

我的示例使用mtcars,但这会转化为任何数据集。

library(purrr)

# keep all columns with any value less than or equal to 10
mtcars %>% 
  keep(~ any(. <= 10))

# remove all columns with all values greater than 10
mtcars %>% 
  discard(~ all(. > 10))

您可以根据需要将该功能设置为高级。这将保留一定百分比的值符合条件的列。

# keep all columns where 90% of the values are less than or equal to 10
mtcars %>% 
  keep(~ (sum(. <= 10) / length(.)) > 0.9)

【讨论】:

  • 是否也可以按一定百分比删除列?就像列中超过 90% 的值为 -1 一样?
  • 我还要注意这一切都在select(where(...)) 上下文中工作。这只是你想要去做的事情。
  • 首先感谢,非常好的和简单的方法。我现在要尝试实施:)
  • 出于好奇,上面的解决方案将如何处理,删除缺少一定百分比值的列?
  • 只需使用discard() 而不是keep()!同样的想法,只需要仔细考虑以确保您得到的正是您想要的。
【解决方案2】:

下次尝试放置一些可重现的数据框,但考虑到您要查找的内容,以下应该可行:

library(dplyr)
desired_df <- original_df %>% select_if(~any(. <=-1 ))

【讨论】:

  • *_if() 中的 dplyr 函数已被取代。我相信当前的语法是select(where(~ any(. &lt;= -1)))
  • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-28
  • 2020-12-05
  • 1970-01-01
  • 2017-11-26
  • 2021-08-19
  • 2014-02-27
相关资源
最近更新 更多