dplyr mutate on range of columns

  • A+
Category:Languages

I would like to make an operation on a range of columns on a data frame. Let us say this dataset is:

set.seed(15) df <- data.frame(id=letters[1:10], matrix(runif(5*10), nrow=5)) %>% dplyr::rename(O6 = X7) 

I think that it is quite obvious what I want to achieve with:

df %>% rowwise() %>% mutate(minval_X3_X8 = min(X3:X8)) 

ie to get the result of:

df %>% rowwise() %>% mutate(minval_X3_X8 = min(X3, X4, X5, O6, X7, X8)) 

My initial try with X3:X8 doesn't give any error message, so I am wondering:
1. What is the best way to achieve the desired output using dplyr (that I get the min/max/average etc. value from columns X3 to X8)
2. What am I actually getting when using X3:X8

Many thanks !

Ps. it would be great if the solution to this includes a possibility to also do:

df %>% rowwise() %>% mutate(minval_all_but_ex_rownames = min(-id)) 

 


With tidyverse, we can do

1) With reduce and pmin

library(tidyverse) df %>%   select(X3:X8) %>%    reduce(pmin) %>%    mutate(df, minval_X3_X8 = .) # id        X1        X2        X3        X4         X5        X6        O6 #1   a 0.6021140 0.9888592 0.1046694 0.8417851 0.80372740 0.6590069 0.4985587 #2   b 0.1950439 0.8151934 0.6461509 0.4474437 0.79334595 0.1069735 0.2567427 #3   c 0.9664587 0.2539684 0.5090904 0.9646670 0.35756312 0.1483839 0.4916694 #4   d 0.6509055 0.6872308 0.7066286 0.1411871 0.05800106 0.9277570 0.1174759 #5   e 0.3670719 0.8314290 0.8623137 0.7767125 0.56574614 0.4763697 0.5128062 #6   f 0.6021140 0.9888592 0.1046694 0.8417851 0.80372740 0.6590069 0.4985587 #7   g 0.1950439 0.8151934 0.6461509 0.4474437 0.79334595 0.1069735 0.2567427 #8   h 0.9664587 0.2539684 0.5090904 0.9646670 0.35756312 0.1483839 0.4916694 #9   i 0.6509055 0.6872308 0.7066286 0.1411871 0.05800106 0.9277570 0.1174759 #10  j 0.3670719 0.8314290 0.8623137 0.7767125 0.56574614 0.4763697 0.5128062 #          X8        X9       X10 minval_X3_X8 #1  0.6578783 0.9152619 0.4291725   0.10466936 #2  0.1215491 0.4574306 0.3302786   0.10697354 #3  0.5159349 0.9210739 0.7528325   0.14838386 #4  0.3016811 0.2591188 0.8438981   0.05800106 #5  0.7603278 0.3437781 0.0108724   0.47636970 #6  0.6578783 0.9152619 0.4291725   0.10466936 #7  0.1215491 0.4574306 0.3302786   0.10697354 #8  0.5159349 0.9210739 0.7528325   0.14838386 #9  0.3016811 0.2591188 0.8438981   0.05800106 #10 0.7603278 0.3437781 0.0108724   0.47636970 

2) Or convert the column names to symbols and do an evaluation

df %>%     mutate(minval_X3_X8 = pmin(!!! rlang::syms(names(.)[3:8]))) 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: