Add minimum value column for selected columns

dplyr

#1

I want to add new column with minimum value by row but i would like to avoid write all column names because I have a lot of columns to select minimum value.

I would like to avoid write

df %>% mutate(newcol = min(column8, column9, column10, column11, column12, column13, column14, na.rm = T))

I wrote the next code but it doesn’t work

df %>% mutate(newcol = min(column8:column14, na.rm = T))

What is wrong?


#2

One way to do it is by using dplyr and rowwise()

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
tribble(~col1, ~col2,
        1,     2,
        3,     5,
        4,     2) %>%
  rowwise() %>%
  mutate(min(col1, col2))
#> Source: local data frame [3 x 3]
#> Groups: <by row>
#> 
#> # A tibble: 3 x 3
#>    col1  col2 `min(col1, col2)`
#>   <dbl> <dbl>             <dbl>
#> 1  1.00  2.00              1.00
#> 2  3.00  5.00              3.00
#> 3  4.00  2.00              2.00