I am fairly new with R and I use the old-school for-loop. I'm trying to code more efficiently by using dplyr to make the processing of my data faster but I am ever confused with lists. I have a simple dataset below:
df <- data_frame(group = sort(rep(1:3, 20)),
values = signif(runif(60), 2),
thresh = ifelse(values > 0.6, TRUE, FALSE))
df %>% group_by(group) %>% group_map(~which(.$thresh == TRUE))
From the output of group_map() above, how do I, 1.) create a new column that contains row names of thresh == TRUE only and the rest are NA, and 2.) create another column that contains the maximum value among the TRUE values from thresh. To illustrate, I desire my final dataframe to be somewhat like this:
group values thresh idex max
1 1 0.77 TRUE 1 NA
2 1 0.32 FALSE NA NA
3 1 0.06 FALSE NA NA
4 1 0.33 FALSE NA NA
5 1 0.51 FALSE NA NA
6 1 0.053 FALSE NA NA
7 1 0.92 TRUE 7 0.92
8 1 0.44 FALSE NA NA
...
...
I thought about making a code but I'm stuck after group_map:
dff %>% group_by(group) %>%
group_map(~which(.$thresh == TRUE)) %>%
mutate(idex = *row_names_in_the_column_blank_are_NA*,
max = max(*values_from_the_indices*))
What is the best way to do this? Thanks!