lundi 29 mars 2021

Find Date in Data Frame in R

I'm trying to use a list of dates to find the same date in a data frame and using ifelse loop to add a new column. Here is the code:

library(lubridate)
df <- tibble(DateCol = seq(ymd("2021-01-01"),ymd("2021-05-31"),"days"))

df2 <- c("2021-02-04","2021-02-07","2021-02-17","2021-02-25")

for (i in 1:length(df$DateCol)) {
  if (df$DateCol[i] == df2) {
    df$ValueCol[i] <- "1"
    } else {
      df$ValueCol[i] <- "0"
      return(i)
    }
  }

The final df I get only has the first date of df2 is 1 in df$ValueCol. Not sure how to make this loop work, seems like there are some mistakes in the df$DateCol[i] == df2 part.

Aucun commentaire:

Enregistrer un commentaire