For a data frame, I need to find the minimum and maximum values, by row, for an unknown number of columns from column 2 onwards. Here is an example:
library(tidyverse)
# test data
(test_data <- tibble(id = c(1:9),
x = runif(9),
x2 = runif(9),
x3 = runif(9)))
samples = 100
# This example, which specifies the column names, correctly finds the min and max values by row
(test_1 <- test_data %>%
rowwise() %>%
mutate(min_val = min(x, x2, x3), max_val = max(x, x2, x3)))
# This example does not
(test_2 <- test_data %>%
rowwise() %>%
mutate(min_val = min(x:x3), max_val = max(x:x3)))
What I actually want to do is something like
mutate(min_val = min([,2:samples+1]), max_val = max([,2:samples+1])))
because (1) I wish to retain the id column (for later joining with another data frame), and (2) specifying by column position seems an obvious way of doing this as I am unconcerned with the column name and samples may be large.
Thank you!
Edited example
This (as suggested)
test_data %>%
nest(-id) %>% # nest rest of columns apart from id
mutate(min_val = map(data, min), # get min and max
max_val = map(data, max)) %>%
unnest()
works on the original test data. However, the real-world data has repetitions of id, e.g.
(test_data <- tibble(id = c(1:9, 1:9),
x = runif(18),
x2 = runif(18),
x3 = runif(18)))
and this results in 'Error: All nested columns must have the same number of elements.'.