【问题标题】:R-Select rows that meet specific criteria across hundreds of columns in RR-选择满足 R 中数百列的特定条件的行
【发布时间】:2019-02-15 10:16:32
【问题描述】:

我有一个如下所示的数据框,但包含数百行和列,这使得 R 中的传统过滤成为一项挑战。

简化图如下:

The rows represent values from a test and the columns represent different treatments

如何为每个“治疗”列选择值介于 -0.5 和 1 之间的所有行(即测试)并将其生成为输出?非常感谢您的想法!

【问题讨论】:

  • 你能提供一个reprex吗? stackoverflow.com/questions/5963269/…
  • 在作为示例提供的“数据框”的超链接图像中,我想选择以下条目(行/列格式):test8/d1,tests15,16/d2,tests 4 ,6,16, 17, 18/d3, test18/d4, 和 test 3/d5。希望这可以澄清吗?
  • “选择条目”是什么意思?你希望结果是什么样的?你想要一个向量、一个数据框还是其他东西?您想保留有关这些值来自哪些列或行的任何信息吗?
  • 我要把这个数据集变成一个长文件,将d1 折叠到d5 到一个名为d 的列中,添加一个time 列,其值为1 到@987654328 @。然后你可以简单地选择你想要的行。如果您使用的是 tidyverse,请使用 'tidy' 数据。
  • 这是一个最优雅的解决方案,也是整洁数据强大功能的绝佳示例。谢谢!!

标签: r dataframe filter dplyr subset


【解决方案1】:

创建示例数据:

df <- data.frame(
    test = paste0("test", 1:18),
    d1 = c(rep(-57, 7), 0, rep(-99, 10)),
    d2 = c(rep(-4, 14), 1, 0.1, -99, -99),
    d3 = c(rep(-89, 3), 0.99, -47, 0.8, rep(-55, 8), -1.56, 0.1, 1, 0),
    d4 = c(rep(-99, 6), rep(-57, 5), 0.7, -3, -13, -99, 0.98, -99, 0.99),
    d5 = c(rep(-57, 2), 0.4, rep(-99, 14), -57),
    stringsAsFactors = FALSE
)

如果你只需要抓取元素:

# get TRUE/FALSE matrix of whether element meets your criteria
meets_criteria <- sapply(df[,-1], function(x) x >= -0.5 & x <= 1)

# "extract" elements that meet your criteria; result is a vector
df[,-1][meets_criteria]

如果您还想保留与元素关联的行/列值

(这遵循上面 cmets 中 @thelatemail 的方法):

# reshape to long
dflong <- tidyr::gather(df, dvar, dvalue, d1:d5)

# subset to meet your criteria
dflong[dflong$dvalue >= -0.5 & dflong$dvalue <= 1, ]

【讨论】:

  • 谢谢 Dan - 这很有效(尽管我应该提到我需要在最终结果中保留“测试”行名称)。 “thelatemail”整理的解决方案解决了问题!
  • 再次感谢丹!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 2022-07-30
  • 2022-08-18
  • 1970-01-01
  • 2014-02-18
相关资源
最近更新 更多