80

给定一个数据框“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

期望的结果,“bar”:

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

2 回答 2

135

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

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

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

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

foo[foo$location == "there", ]
于 2010-08-10T02:28:39.910 回答
4

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

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

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

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

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

或您所期望的特定列。

    foo[foo[ ,c(1,5,9)], ]
于 2018-10-01T04:50:19.960 回答