gpt4 book ai didi

r - 根据列中的条件对数据框中的行进行子集化/过滤

转载 作者:行者123 更新时间:2023-12-03 05:40:49 27 4
gpt4 key购买 nike

给定一个数据框“foo”,我如何才能只选择“foo”中的那些行,例如foo$location =“那里”

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

最佳答案

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

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

请注意,您可以使用 &| 将多个条件串起来以创建复杂的子集。

第二种是索引方法。您可以使用数字切片或 bool 切片对 R 中的行进行索引。 foo$location == "there" 返回由 TF 值组成的向量,其长度与 foo 的行相同。您可以执行此操作以仅返回条件返回 true 的行。

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

关于r - 根据列中的条件对数据框中的行进行子集化/过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3445590/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com