eclo.qh
eclo.qh

Reputation: 175

How to correctly subset a dataframe in r?

I want to subset a dataframe, and the following creates a dataframe:

col1<-c(1:22 )
col2<-c(0,-19,1,-30,15,60,15,16,19
        ,19,1,13,13,24,60,19,160,72
        ,10,19,14,-78)
col3<-c ( NA,2.190,NA,NA, -5.000, NA,
         1.700,4.220,NA,NA,NA,2.000,
         6.340,9.000,-5.000,NA,4.750,
         NA,NA,NA,2.560,2.560)
mydata<-data.frame(col1,col2,col3)

I want to subset this dataframe that both the values in col2 and col3 are larger than 0, then my next syntax is:

mydata<-mydata[mydata$col2>0 & mydata$col3>0,]

Obviously the dataframe has been changed, so What is the problem with my syntax?

This is the dataframe before:

my dataframe before

... and this is the dataframe after:

my dataframe after

Upvotes: 3

Views: 127

Answers (1)

Alexander Radev
Alexander Radev

Reputation: 662

How about using the subset function:

subset(mydata, col2>0 & col3>0)

Upvotes: 4

Related Questions