Search code examples
rweathermonthcalendar

How to change cell value within a column in reference to another cell value within another column in r?


I would like to replace the 'month' value by looking at the 'week' value. If it is week 52 then the month should be 12. How to do that across the data?

Example data:

   year month week
    2010 1 52
    2010 12 52
    2011 1 52
    2011 12 52
    2012 1 52
    2012 12 52

expected data:

year month week
2010 12 52
2010 12 52
2011 12 52
2011 12 52
2012 12 52
2012 12 52

Solution

  • As @MrSmithGoesToWashington pointed out, if you look from the time perspective, it is not possible. But if you are just asking how to change any value based on the value in another column, you can do sth like that.

    library(dplyr)
    df <- data.frame(year = c(2010, 2010),
                     month = c(1, 12),
                     week = c(52, 52))
    
    df %>% mutate(month = ifelse(week == 52, 12, df$month))