subsetting a dataframe by a condition in R [duplicate]

限于喜欢 提交于 2019-12-13 23:16:05

问题


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)


来源:https://stackoverflow.com/questions/33651477/subsetting-a-dataframe-by-a-condition-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!