Home > Mobile >  add new column represent the number of occurrence of weekday within the specific month in R datafram
add new column represent the number of occurrence of weekday within the specific month in R datafram

Time:12-21

I would like to add a new column in my data frame (image1), this new column represents the number of occurrences of weekdays within the specific month, at the end, I need to have something like the "working day in the month" in "image2"

enter image description here

enter image description here

how I can achieve this result in R?

CodePudding user response:

assuming the dataframe is df, you could do something like this

df <- df %>% mutate(month = month(date), year = year(date))
df <- df %>% group_by(day_name, month)
df <- df %>% summarize(working_day_in_month = n())
df <- df %>% arrange(day_name)

df

new df

CodePudding user response:

This is a solution if you only have one month

for(i in 1:length(df$day_name))
{
  b<- as.character(df[i,2])
  c<- a[1:i,2]
  df$working_day[i] <- length(which(c==b))
}
  • Related