【问题标题】:Subset / filter rows in a data frame based on a condition in a column根据列中的条件对数据框中的行进行子集/过滤
【发布时间】:2011-03-27 14:41:57
【问题描述】:

给定一个数据框“foo”,我怎样才能从“foo”中只选择那些行,例如foo$location = "there"?

foo = data.frame(location = c("here", "there", "here", "there", "where"), x = 1:5, y = 6:10)
foo
#   location x  y
# 1     here 1  6
# 2    there 2  7
# 3     here 3  8
# 4    there 4  9
# 5    where 5 10

期望的结果,“条”:

#   location x y
# 2    there 2 7
# 4    there 4 9

【问题讨论】:

    标签: r dataframe subset r-faq


    【解决方案1】:

    以下是两种主要方法。我更喜欢它的可读性:

    bar <- subset(foo, location == "there")
    

    请注意,您可以使用&amp;| 将许多条件串在一起以创建复杂的子集。

    第二个是索引方法。您可以使用数字或布尔切片对 R 中的行进行索引。 foo$location == "there" 返回与 foo 的行长度相同的 TF 值向量。您可以这样做以仅返回条件返回 true 的行。

    foo[foo$location == "there", ]
    

    【讨论】:

    • .@JoFrhwld - subset() 不是首选方法吗?详细讨论here
    • 是否有一种简单的方法可以同时访问子集和 foo 减去子集?我想将我的数据拆分为 bar 和 (foo-bar)。显然,我可以用 != 重复上述内容,但是否有单行方式?
    • 您好,我正在学习索引,我有一个问题。假设可以在此处提取一组特定的列,例如,foo[foo$location == '"there",5:8] 如果我尝试为这些列赋值会发生什么:foo[foo$location == "there",5:8] &lt;-FALSE
    • 解释得很好!
    【解决方案2】:

    只是为了扩展上面的答案,您还可以索引您的列,而不是指定列名,这也可能有用,具体取决于您在做什么。鉴于您的位置是第一个字段,它看起来像这样:

        bar <- foo[foo[ ,1] == "there", ]
    

    这很有用,因为您可以对列值执行操作,例如遍历特定列(您也可以通过索引行号来执行相同操作)。

    如果您需要对多个列执行某些操作,这也很有用,因为您可以指定一系列列:

        foo[foo[ ,c(1:N)], ]
    

    或如您所料的特定列。

        foo[foo[ ,c(1,5,9)], ]
    

    【讨论】:

      猜你喜欢
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-18
      • 1970-01-01
      • 2013-08-15
      • 2022-01-03
      相关资源
      最近更新 更多