Reputation: 442
I would like to understand how I can get the row-wise minimum for a set of columns that are defined in a vector of strings, i.e. how to get the following output with the following input:
Input:
t <- data.frame(x= c(1,2,3,4), y= c(2,3,4,5), z = c(4,5,6,7))
vars. <- c('x', 'y')
My (not working) suggestion:
t %>% rowwise %>% mutate(min_x_y = min(vars(vars.)))
Output should be:
x y z min_x_y
1 1 2 4 1
2 2 3 5 2
3 3 4 6 3
4 4 5 7 4
Upvotes: 0
Views: 285
Reputation: 459
Yet another alternative to the approaches already suggested would be to use a combination of tidy evaluation and pmin
:
# convert character vector of variable names into symbols
vars. <- c('x', 'y') %>% dplyr::syms()
# use tidy evaluation to pass symbols to pmin inside a mutate call
t %>%
mutate(min_x_y = pmin(!!!vars.))
#> x y z min_x_y
#> 1 1 2 4 1
#> 2 2 3 5 2
#> 3 3 4 6 3
#> 4 4 5 7 4
Upvotes: 2
Reputation: 388807
We can use pmap_dbl
from purrr
.
library(dplyr)
library(purrr)
t %>% mutate(min_x_y = pmap_dbl(select(., vars.), min))
# x y z min_x_y
#1 1 2 4 1
#2 2 3 5 2
#3 3 4 6 3
#4 4 5 7 4
A base R version would be
t$min_x_y <- do.call(pmin, t[vars.])
Upvotes: 3
Reputation: 181
You can do that in different ways, one is;
t <- data.frame(x= c(1,2,3,4), y= c(2,3,4,5), z = c(4,5,6,7))
vars. <- c('x', 'y')
t$min_x_Y=t(as.data.frame(t(t)) %>%
summarise_all(funs(min)))
Upvotes: 0