eclo.qh eclo.qh - 5 days ago 6
R Question

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

Answer

How about using the subset function:

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