R - 子集数据如果条件 [英] R - subset data if conditions

查看:39
本文介绍了R - 子集数据如果条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用逻辑条件对数据进行子集化.

How can I subset data with logical conditions.

假设我有如下数据.我想以所有动物都具有 FCR 记录的第一个条件对数据集进行子集化,然后我想将所有动物与新数据集中的这些动物放在同一圈内.

Assume that I have data as below. I would like to subset data set with first condition that all animals having FCR record, then I would like to take all animals in same pen with these animals in new data set.

animal  Feed    Litter  Pen 
1   0.2 5   3
2   NA  5   3
3   0.2 5   3
4   0.2 6   4
5   0.3 5   4
6   0.3 4   4
7   0.3 5   3
8   0.3 5   3
9   NA  5   5
10  NA  3   5
11  NA  3   3
12  NA  3   5
13  0.4 7   3
14  0.4 7   3
15  NA  7   5

推荐答案

我假设FCR 记录"(在您的问题中)与Feed"相关.然后,如果我正确理解了这个问题,你可以这样做:

I'm assuming that "FCR record" (in your question) relates to "Feed". Then, if I understand the question correctly, you can do this:

split(df[complete.cases(df),], df[complete.cases(df), 4])
# $`3`
#    animal Feed Litter Pen
# 1       1  0.2      5   3
# 3       3  0.2      5   3
# 7       7  0.3      5   3
# 8       8  0.3      5   3
# 13     13  0.4      7   3
# 14     14  0.4      7   3
# 
# $`4`
#   animal Feed Litter Pen
# 4      4  0.2      6   4
# 5      5  0.3      5   4
# 6      6  0.3      4   4

在上面,complete.cases 删除任何不完整的观察.如果您需要匹配特定变量上的参数,您可以使用诸如 df[!is.na(df$Feed), ] 之类的东西,而不是 complete.cases.然后,split 创建一个由 Pen 分割的 data.frames 列表.

In the above, complete.cases drops any of the incomplete observations. If you needed to match the argument on a specific variable, you can use something like df[!is.na(df$Feed), ] instead of complete.cases. Then, split creates a list of data.frames split by Pen.

这篇关于R - 子集数据如果条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆