Gunnerfan
Gunnerfan

Reputation: 123

Subset in R between 2 Months over a Range of Days

I have been subsetting data using this code below.

setwd("C:/Users/A/Desktop")
vf <- read.csv("Height.csv", header = TRUE)
#Insert month and Day(s) desired
vf1 <- vf [ which(vf$Month==9 & vf$Day>0 & vf$Day <31), ]
vf2 <- vf1[c(-1,-2,-3)]

When I try to subset from April 20th to May 20th, I use this code (shown below) and it subsets nothing

vf1 <- vf [ which(vf$Month==4 & vf$Month ==5 & vf$Day>19 & vf$Day <32), ]

I also try another way (below) and get an error

vf1 <- vf [ which(vf$Month==4 & vf$Day>19 & vf$Day <31), which(vf$Month ==5 & vf$Day>19 & vf$Day <32), ]
Error in `[.data.frame`(vf, which(vf$Month == 4 & vf$Day > 19 & vf$Day <  : 
  undefined columns selected

Can someone please explain what is being done incorrectly?

Upvotes: 0

Views: 69

Answers (1)

ja-thomas
ja-thomas

Reputation: 101

As @JoshuaUlrich said, the month of one observation can't be two values at the same time. Something like that would work:

vf1 <- vf [ which( vf$Month==4 & vf$Day>19 | vf$Month ==5 & vf$Day <32 ), ]

So you are saying if Month is 4, Day must be larger 19 or if Month is 5, Day must be smaller 32.

Upvotes: 1

Related Questions