【问题标题】:R: selecting items matching criteria from a vectorR:从向量中选择符合条件的项目
【发布时间】:2012-04-08 20:29:22
【问题描述】:

我在 R 中有一个数字向量,它由负数和正数组成。我想根据符号(暂时忽略零)将列表中的数字分成两个单独的列表:

  • 一个只包含负数的新向量
  • 另一个只包含正数的向量

文档展示了如何在数据框中选择行/列/单元格 - 但这不适用于向量 AFAICT。

怎么做(没有for循环)?

【问题讨论】:

  • 原来,我可以简单地在选择标准中使用向量的名称。例如:negs

标签: r


【解决方案1】:

这很容易完成(添加了对 NaN 的检查):

d <- c(1, -1, 3, -2, 0, NaN)

positives <- d[d>0 & !is.nan(d)]
negatives <- d[d<0 & !is.nan(d)]

如果你想同时排除 NA 和 NaN,is.na() 对两者都返回 true:

d <- c(1, -1, 3, -2, 0, NaN, NA)

positives <- d[d>0 & !is.na(d)]
negatives <- d[d<0 & !is.na(d)]

【讨论】:

  • 如何从选择中忽略 NaN?
  • 我已经编辑了答案。请注意,d>0 是模式逻辑向量,与 is.nan(d) 和 is.na(d) 相同。将 & 应用于逻辑模式的两个向量会执行“逻辑”操作。
【解决方案2】:

这可以通过使用“方括号”来完成。 创建一个新向量,其中包含那些大于零的值。由于使用了比较运算符,它将表示布尔值。因此,方括号用于获取确切的数值。

d_vector<-(1,2,3,-1,-2,-3)
new_vector<-d_vector>0 
pos_vector<-d_vector[new_vector]
new1_vector<-d_vector<0
neg_vector<-d_vector[new1_vector]

【讨论】:

    【解决方案3】:

    purrrpackage 包含一些过滤向量的有用函数:

    library(purrr)
    test_vector <- c(-5, 7, 0, 5, -8, 12, 1, 2, 3, -1, -2, -3, NA, Inf, -Inf, NaN)
    
    positive_vector <- keep(test_vector, function(x) x > 0)
    positive_vector
    # [1]   7   5  12   1   2   3 Inf
    
    negative_vector <- keep(test_vector, function(x) x < 0)
    negative_vector
    # [1]   -5   -8   -1   -2   -3 -Inf
    

    你也可以使用discard函数

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-20
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2011-05-17
      相关资源
      最近更新 更多