I have the following data set:
df <- tribble(
~id, ~name, ~day_1, ~day_2, ~day_3, ~day_4, ~rank,
"101", "a", 5, 2, 1, 8, '1',
"202", "b", 8, 4, 5, 5, '2',
"303", "c", 10, 6, 9, 6, '3',
"404", "d", 12, 8, 5, 7, '4',
"505", "e", 14, 10, 7, 9, '5',
"607", "f", 5, 2, 1, 8, '6',
"707", "g", 8, 4, 5, 5, '7',
"808", "h", 10, 6, 9, 6, '8',
"909", "k", 12, 8, 5, 7, '9',
"1009", "l", 14, 10, 7, 9, '10',
)
After creating the top
variable thanks to @Edward and grouping the data by top
, I've taken the median of values for each column that starts with day. Here is the code:
df %>%
mutate(top = ifelse(rank <= 1, 1,
ifelse(rank <= 3, 3,
ifelse(rank <= 5, 5,
ifelse(rank <= 7, 7,
ifelse(rank <= 8, 8, 10)))))) %>%
group_by(top) %>%
summarize(day_1 = median(as.numeric(day_1), na.rm = TRUE),
day_2 = median(as.numeric(day_2), na.rm = TRUE),
day_3 = median(as.numeric(day_3), na.rm = TRUE),
day_4 = median(as.numeric(day_4), na.rm = TRUE))
And here is the result:
# A tibble: 6 x 5
top day_1 day_2 day_3 day_4
<dbl> <dbl> <dbl> <dbl> <dbl>
1 1 5 2 1 8
2 3 10 6 7 6
3 5 13 9 6 8
4 7 6.5 3 3 6.5
5 8 10 6 9 6
6 10 12 8 5 7
However, since I have almost forty columns that start with day in my real data set, I would like to use a function to do it more efficiently instead of writing all column names like summarize(day_1 = median(as.numeric(day_1), na.rm = TRUE)
.
Any idea for this?