user1568100
user1568100

Reputation: 11

R - subset data if conditions

How can I subset data with logical conditions.

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

Upvotes: 1

Views: 1140

Answers (2)

Thierry
Thierry

Reputation: 18487

# all animals with Feed data
df[!is.na(df$Feed), ]
# all animals from pens with at least one animal with feed data in the pen
df[ave(!is.na(df$Feed), df$Pen, FUN = any), ]

Upvotes: 1

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193547

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

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.

Upvotes: 2

Related Questions