I need to create a "flag" column within my main data frame that flags rows where the date is within a specific time range. That time range comes from a second data frame. I think I'm just stuck on the ifelse (or if) statement because there are NA's in the flag column. Maybe ifelse isn't the way to go. Here's some sample data:
# main data frame
date <- seq(as.Date("2014-07-21"), as.Date("2014-09-11"), by = "day")
group <- letters[1:4]
datereps <- rep(date, length(group))
groupreps <- rep(group, each = length(date))
value <- rnorm(length(datereps))
df <- data.frame(Date = datereps, Group = groupreps, Value = value)
# flag time period data frame
flag <- data.frame(Group = c("b", "d"),
start = c("2014-08-01", "2014-08-26"),
end = c("2014-08-11", "2014-09-01"))
# Merge flag dates into main data frame
df2 <- merge(df, flag, by = "Group", all.x = T)
# Execute ifelse statement on each row
df2$flag <- "something"
df2$flag <- ifelse(df2$Date >= as.Date(df2$start) & df2$Date <= as.Date(df2$end), "flag", "other")
The result is that in rows where a "start" and "end" date are specified, "flag" and "other" are labeled, but where "start" and "end" are NA, I get Na values for df2$flag
. This happens even when I initiate df2$flag
with "something"
. I want "other"
for all values that are not defined as "flag"
. Look at rows 50:68.
df2[50:68,]
Aucun commentaire:
Enregistrer un commentaire