I am struggling to find the proper way to select a specific row in a dataframe, based on several conditions from different columns and to try to input a given value to that cell. I am trying to find a dplyr based solution, but can’t find any after several hours of trying…
I have created an empty column ‘C’, I want to select for a given ‘A’ (factor) and for the maximum value of ‘B’ (numeric) for that given A (not the max for the entire col B), then I want to write ‘something’ in the corresponding ‘C’ column for that row.
Here is a dummy DF replicating what I am trying to do:
A <- factor(c("19/09/2022", "19/09/2022", "19/09/2022", "20/09/2022", "20/09/2022", "20/09/2022", "21/09/2022", "21/09/2022", "21/09/2022", "22/09/2022", "22/09/2022", "22/09/2022"))
B <- c(0.1781223, 3.3488114, 4.1476595, 5.8611553, 10.9773307, 16.9890155, 24.0428161, 35.1776457, 40.4551331, 49.5663783, 63.9132875, 64.6766946)
df <- data.frame(A, B)
I create an empty column, in which I want to write.
df$C <- NA
I have tried something like this, using case_when, but there is an error on the type of B:
df %>%
filter(A == "19/09/2022") %>%
mutate(C = case_when(
B == max(B, na.rm = T) ~ "something",
B ~ NA))
Thank you for your help!