I would like to calculate the day difference by the number of row of groups:
v = data.frame(group = c('a','a','b','c','c'),days_difference = c(0,56,0,0,23))
v %>% group_by(group) %>% filter(n() == 1) %>% mutate(days_difference = (difftime(as.Date('01-01-2020', "%d-%m-%Y"),as.Date('04-06-2018',"%d-%m-%Y"))))
In the above code, if the length of groups is equal to one, then the days_difference will change from 0 to difftime(as.Date('01-01-2020', "%d-%m-%Y"),as.Date('04-06-2018',"%d-%m-%Y")).
However, I need to use dummy variables in order to insert the result into the original data.frame.
Is there anyways to use inplace in r? Or how to use ifelse in mutate function?
Please give me some suggestions, thank you!
>Solution :
We could use base R’s ifelse:
Usage: after mutate we set the new column name then = and then ifelse(). Within ifelse the arguments are: ifelse(condition, result if TRUE, result if FALSE). It is always this macro. In the condition term you can combine multiple conditions. Like in your case we check n() == 1 AND days_difference == 0. After doing the condition we set a coma. The next argument is what should happen if this condition is TRUE in your case difftime(as.Date('01-01-2020', "%d-%m-%Y"), as.Date('04-06-2018',"%d-%m-%Y")) then we set again a coma and the last argument is what will happen if the condition is FALSE in your case (the values in days_difference column.
Type ?ifelse in your console and see the documentation.
library(dplyr)
library(tidyverse)
v %>%
group_by(group) %>%
mutate(
days_difference = ifelse(n() == 1 & days_difference == 0,
difftime(as.Date('01-01-2020', "%d-%m-%Y"), as.Date('04-06-2018',"%d-%m-%Y")),
days_difference)
)
group days_difference
<chr> <dbl>
1 a 0
2 a 56
3 b 576
4 c 0
5 c 23