subsetting a dataframe by a condition in R [duplic

2019-10-20 22:17发布

问题:

This question already has an answer here:

  • Filtering a data frame by values in a column [duplicate] 3 answers

I have the following data with the ID of subjects.

V1
1   2
2   2
3   2
4   2
5   2
6   2
7   2
8   2
9   2
10  2
11  2
12  2
13  2
14  2
15  2
16  4
17  4
18  4
19  4
20  4
21  4
22  4
23  4
24  4

I want to subset all the rows of the data where V1 == 4. This way I can see which observations relate to subject 4.

For example, the correct output would be

16  4
17  4
18  4
19  4
20  4
21  4
22  4
23  4
24  4

However, the output I'm given after subsetting does not give me the correct rows . It simply gives me.

V1
1  4
2  4
3  4
4  4
5  4
6  4
7  4
8  4

I'm unable to tell which observations relate to subject 4, as observations 1:8 are for subject 2.

I've tried the usual methods, such as

condition<- df == 4
df[condition]

How can I subset the data so I'm given back a dataset that shows the correct row numbers for subject 4.

回答1:

I've managed to find a solution since posting.

newdf <- subset(df, V1 == 4). 

However i'm still very interested in other solutions to this problems, so please post if you're aware of another method.



回答2:

You can also use the subset function:

subset(df,df$V1==4)