简体   繁体   中英

Get a value based on the value of another column in R - dplyr

i got this df:

df <- data.frame(month = c(1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4),
                 day   = c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5),
                 flow  = c(2,5,7,8,5,4,6,7,9,2,NA,1,6,10,2,NA,NA,NA,NA,NA))

and i want to reach this result:

   month   day  flow   dayofminflow
 1     1     1     2     1
 2     1     2     5     1
 3     1     3     7     1
 4     1     4     8     1
 5     1     5     5     1
 6     2     1     4     5
 7     2     2     6     5
 8     2     3     7     5
 9     2     4     9     5
10     2     5     2     5
11     3     1    NA     2
12     3     2     1     2
13     3     3     6     2
14     3     4    10     2
15     3     5     2     2
16     4     1    NA    NA
17     4     2    NA    NA
18     4     3    NA    NA
19     4     4    NA    NA
20     4     5    NA    NA

I was using this solution, but it returns NA when the first value is NA:

newdf <- df %>% group_by(month) %>% mutate(Val=day[flow==min(flow)][1])

And this solution returns an error when all data is NA:

library(dplyr)
df <- df %>%
       group_by(month) %>% 
       mutate(dayminflowofthemonth = day[which.min(flow)]) %>%
       ungroup

You would just change the default na.rm = TRUE in min() from the first solution to ignore NAs?

df %>% 
    group_by(month) %>% 
    mutate(dayofminflow = day[which(min(flow, na.rm = TRUE) == flow)][1])

# A tibble: 20 x 4
# Groups:   month [4]
   month   day  flow dayofminflow
   <dbl> <dbl> <dbl>        <dbl>
 1     1     1     2            1
 2     1     2     5            1
 3     1     3     7            1
 4     1     4     8            1
 5     1     5     5            1
 6     2     1     4            5
 7     2     2     6            5
 8     2     3     7            5
 9     2     4     9            5
10     2     5     2            5
11     3     1    NA            2
12     3     2     1            2
13     3     3     6            2
14     3     4    10            2
15     3     5     2            2
16     4     1    NA           NA
17     4     2    NA           NA
18     4     3    NA           NA
19     4     4    NA           NA
20     4     5    NA           NA

Though you get a warning no non-missing arguments to min; returning Inf no non-missing arguments to min; returning Inf from month 4 since all flow values are NA.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM