Home > database >  Sum (or not) a value based on condition of another column in R
Sum (or not) a value based on condition of another column in R

Time:02-06


Let's imagine the following data. Columns A, B, and C. Column A contains years (eg.2022, 2025, 2030, etc). Column B contains a month (eg. 2, 7,8, etc). I need to create a column C that does the following "if else".

If B >=6, then C = A 1.
If B is smaller than 6, then C = A.

Can anyone help me please? Have a good day

CodePudding user response:

df$c <- ifelse(df$b >= 6, df$a 1, df$a)

CodePudding user response:

Here is a dplyr solution using an ifelse statement:

library(dplyr)

df %>% 
  mutate(C = ifelse(B >= 6, A 1, A))
      A     B     C
  <dbl> <dbl> <dbl>
1  2022     2  2022
2  2025     7  2026
3  2030     8  2031
df <- structure(list(A = c(2022, 2025, 2030), B = c(2, 7, 8)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -3L))
  •  Tags:  
  • Related