I'm trying to figure out how to run a simple operation on a column based on a condition from another column. In this specific case, I'm trying to add 1 to a column based on whether or not another column is 10 or more (converting calendar year to fiscal year). I need to make that conversion, but what I really need is a general solution for this type of problem because it comes up a lot.
I'm looking for something like:
if 'column a' meets condition, then do this thing to 'column b' else do nothing (or a different thing to 'column b')
I'm more used to python but am forced to use R for the time being, so I'm struggling a little bit. The equivalent code in python would be:
df['fiscal year'] = np.where(df['month'] >= 10, year + 1, year)
Starting with
df$date <- as.Date(df$date)
df$year <- format(df$date, format = "%Y")
df$month <- format(df$date, format = "%m")
df$year <- as.integer(df$year)
df$fiscal_year <- df$year
What I've tried so far are the below code snippets
df$fiscal_year[df$month >= 10] <- df$year + 1
which gave a warning: number of items to replace is not a multiple of replacement length
and returned odd results, some rows worked correctly, some returned strange results. Although they only occurred if the condition was met, such as converting 2017 to 2024. Nothing went wrong if the condition wasn't met.
df$fiscal_year <- df %>% ifelse(month >= 10, df$fiscal_year + 1 , df$fiscal_year)
This one errored out, with "unused argument (df$fiscal_year)
I think you need the filter
[df$month >= 10]on both sides of the<-.