How to replace NAs for a length variable?

#Could someone help me please?
#I have a dataframe with two variables:

data<-data.frame(people=c("john","mary"),
day=c(-10,-50,-25,-25,-1,-20,20,20,30,20,NA,NA,NA,NA))

#For each person, If NA I would like to replace it with the minimum value of the variable days
#the result should be something like:
newdata<-data.frame(people=c("john","mary"),
day=c(-10,-50,-25,-25,-1,-20,20,20,30,20,-25,-50,-25,-50))

newDay <- ifelse(is.na(day),min(day,na.rm = TRUE),day)

Thank you very much Startz. But, the results is different that i need. Its return the minimum for all variable day. I need to have it for each person separately.

You just need to integrate @startz's code into the data frame.

data<-data.frame(people=c("john","mary"),
                 day=c(-10,-50,-25,-25,-1,-20,20,20,30,20,NA,NA,NA,NA))

library(dplyr)

data %>% 
  group_by(people) %>% 
  mutate(day_new = if_else(is.na(day), min(day, na.rm = T), day))

#> # A tibble: 14 x 3
#> # Groups:   people [2]
#>    people   day day_new
#>    <chr>  <dbl>   <dbl>
#>  1 john     -10     -10
#>  2 mary     -50     -50
#>  3 john     -25     -25
#>  4 mary     -25     -25
#>  5 john      -1      -1
#>  6 mary     -20     -20
#>  7 john      20      20
#>  8 mary      20      20
#>  9 john      30      30
#> 10 mary      20      20
#> 11 john      NA     -25
#> 12 mary      NA     -50
#> 13 john      NA     -25
#> 14 mary      NA     -50

Created on 2022-03-06 by the reprex package (v2.0.1)

Thanks @startz and @ibertchen.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.