Create interest instead of melt / cast amounts

A simple example. I would like to create a data frame with percentages using cast / melt instead of sums.

Example.

eg <- data.frame( Time = factor(c(1,2,1,2)), A1 = c(0, 0, 1, 1), A2 = c(1, 1, 1, 1), B1 = c(0, 0, 0, 0) ) eg.m <- melt(eg,id="Time") eg.c <- cast(eg.m,Time ~ variable, sum, margins="grand_row") 

In the above example, I can get the amount and amount. Instead of producing a sum, is there a way to produce a percentage in each cell, that is, the sum of the cell / gran _row? I know I can do some things here using ddply and reshape, but I wonder if there is a more elegant solution.

Here is an example of what I'm looking for:

  Time A1 A2 B1 1 1 0.5 0.5 0 2 2 1.0 1.0 0 
+4
source share
1 answer

It’s hard for me to do without two steps. The problem is that you want to run the cumsum / sum function on the output of the dcast operation, if I do not understand what you want.

First it is the way you have it:

 eg.c <- dcast(eg.m,Time ~ variable, sum ) 

Secondly, just apply the cumsum / sum function to the columns:

 japply(eg.c, sapply(eg.c, is.numeric ), function(x) cumsum(x)/sum(x) ) Time A1 A2 B1 1 1 0.5 0.5 NaN 2 2 1.0 1.0 NaN 

Where japply is the function I have in my .RProfile:

 # Takes a data.frame and returns a data.frame with only the specified columns transformed japply <- function(df, sel, FUN=function(x) x, ...) { df[,sel] <- sapply( df[,sel], FUN, ... ) df } 
+3
source

Source: https://habr.com/ru/post/1411515/


All Articles