TDo
TDo

Reputation: 744

R-Select some rows with conditions

I have a data frame t1 like this in R

name    age

Kevin   15
Lin     20
Kyte    8

I want to choose all rows in the first 2 rows and age >15. I try t1[1:2 & age>15,] but it doesn't work.

Really appreciate if someone can help. Thanks

Upvotes: 2

Views: 61

Answers (2)

Marta Cz-C
Marta Cz-C

Reputation: 789

If your data is in form of

t1<- data.frame(name=c("Kevin", "Lin", "Kyte"), age=c(15, 20, 8))

then try

 t1[1:nrow(t1)<=2 & t1$age>15,]

The vector 1:2 is shorter than t1$age (or just age if you have it as a variable), so when you compare them R would return a warning.

Upvotes: 1

Nikos
Nikos

Reputation: 3297

The way you are accesing the age column is wrong. Can you try the following:

t1[1:2 & t1$age>15,]

Hope this helps.

Upvotes: 0

Related Questions