Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add 1 (or more generally, perform a simple operation) on a column based on a condition

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’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

I think you need the filter [df$month >= 10] on both sides of the <-.

df$fiscal_year[df$month >= 10] <- df$year[df$month >= 10] + 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading