Dplyr bypasses some columns

What is the dplyr way to apply rowwise to some columns. For example, I want to capture all the columns of V, and turn them into percentages based on the sums of the rows. I show how to do this in the database. What's in the dplyr chain. It would be nice to see the form data.table (although it would be preferable to go to dplyr ).

 x <- data.frame(A=LETTERS[1:5], as.data.frame(matrix(sample(0:5, 25, T), ncol=5))) data.frame(x[1], x[-1]/rowSums(x[-1])) ## A V1 V2 V3 V4 V5 ## 1 A 0.1428571 0.2142857 0.2142857 0.35714286 0.07142857 ## 2 B 0.2000000 0.2000000 0.1500000 0.20000000 0.25000000 ## 3 C 0.3571429 0.2857143 0.0000000 0.07142857 0.28571429 ## 4 D 0.1904762 0.2380952 0.1904762 0.23809524 0.14285714 ## 5 E 0.2000000 0.2500000 0.1500000 0.25000000 0.15000000 library(dplyr) props <- function(x) round(x/sum(x), 2) # does not work x %>% rowwise() mutate(props(matches("^.{2}$"))) 
+7
r data.table dplyr
source share
2 answers

You can combine tidyr spread and gather with dplyr to get the following single pipeline:

 x <- data.frame(A=LETTERS[1:5], as.data.frame(matrix(sample(0:5, 25, T), ncol=5))) y <- x %>% gather(V, val, -A) %>% group_by(A) %>% mutate(perc = val / sum(val)) %>% select(-val) %>% spread(V, perc) 

With tidy data strong> it's pretty easy to get any group sum (rows, columns, or any nested -level index) and calculate percentages. spread and gather take you to and from your input format.

+6
source share

In data.table you can do

 library(data.table) setDT(x) x[, grep("^V",names(DT)) := .SD/Reduce(`+`, .SD), .SDcols = V1:V5] A V1 V2 V3 V4 V5 1: A 0.28571429 0.0000000 0.2857143 0.07142857 0.35714286 2: B 0.23076923 0.2307692 0.3076923 0.15384615 0.07692308 3: C 0.44444444 0.0000000 0.4444444 0.00000000 0.11111111 4: D 0.07142857 0.3571429 0.1428571 0.07142857 0.35714286 5: E 0.00000000 0.2222222 0.3333333 0.44444444 0.00000000 

To calculate the denominator with ignored NA values, I think rowSums is an option, although it will force .SD to the matrix as an intermediate step.

+7
source share

All Articles