Reputation: 23
I have a data frame (set1) with 3 fields - date (date), price (numeric) and event (logical). I would like to create a vector that returns the date when event is TRUE.
I have been able to do this for price: returns a vector of 346 prices
n <- c()
for(i in 1:length(set1$price)){
if(set1$event[i] == TRUE) {
n <- append(n,set1$price[i])
}
}
However, when I try to do the same for date only the first date when event is TRUE is returned: 2001-10-29
n <- c()
for(i in 1:length(set1$date)){
if(set1$event[i] == TRUE) {
n <- append(n,set1$date[i])
}
}
I tried to assign the empty vector as a date field but the result was still the same:
n <- c()
n <- as.Date(as.character(n), format = "%Y%m%d")
Upvotes: 2
Views: 194
Reputation: 99331
You can use [
subsetting on the logical vector event
. For example, here's some made-up data
date <- seq(Sys.Date()-5, Sys.Date(), 1)
event <- c(FALSE, TRUE, TRUE, FALSE, FALSE, TRUE)
(set1 <- data.frame(date, event))
# date event
# 1 2014-11-09 FALSE
# 2 2014-11-10 TRUE
# 3 2014-11-11 TRUE
# 4 2014-11-12 FALSE
# 5 2014-11-13 FALSE
# 6 2014-11-14 TRUE
Then you can subset the date
vector by the event
vector and all the dates for which event is TRUE will be returned.
with(set1, date[event])
# [1] "2014-11-10" "2014-11-11" "2014-11-14"
And you could do the same for the pricing column in your data.
Upvotes: 1